123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- import os
- import zipfile
- from typing import List
- def zip_files(file_paths: List[str], output_zip_path: str, delete_after_zip:bool = True) -> bool:
- """
- 将多个文件压缩为zip文件
-
- Args:
- file_paths: 要压缩的文件路径列表
- output_zip_path: 输出的zip文件路径
-
- Returns:
- bool: True表示压缩成功,False表示失败
- """
- try:
- # 确保输出目录存在
- os.makedirs(os.path.dirname(output_zip_path), exist_ok=True)
-
- with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
- for file_path in file_paths:
- if os.path.exists(file_path):
- # 将文件添加到zip中,保持相对路径结构
- arcname = os.path.basename(file_path)
- zipf.write(file_path, arcname)
- else:
- raise FileNotFoundError(f"文件不存在: {file_path}")
-
- if delete_after_zip:
- for file_path in file_paths:
- os.remove(file_path)
- return True
-
- except Exception as e:
- print(f"压缩文件失败: {e}")
- return False
- def unzip_files(zip_path: str, output_dir: str) -> bool:
- """
- 解压缩zip文件到指定目录
-
- Args:
- zip_path: 要解压的zip文件路径
- output_dir: 解压输出目录
-
- Returns:
- bool: True表示解压成功,False表示失败
- """
- try:
- # 确保输出目录存在
- os.makedirs(output_dir, exist_ok=True)
-
- with zipfile.ZipFile(zip_path, 'r') as zipf:
- zipf.extractall(output_dir)
-
- return True
-
- except Exception as e:
- print(f"解压文件失败: {e}")
- return False
|