files.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import os
  2. import zipfile
  3. from typing import List
  4. def zip_files(file_paths: List[str], output_zip_path: str, delete_after_zip:bool = True) -> bool:
  5. """
  6. 将多个文件压缩为zip文件
  7. Args:
  8. file_paths: 要压缩的文件路径列表
  9. output_zip_path: 输出的zip文件路径
  10. Returns:
  11. bool: True表示压缩成功,False表示失败
  12. """
  13. try:
  14. # 确保输出目录存在
  15. os.makedirs(os.path.dirname(output_zip_path), exist_ok=True)
  16. with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
  17. for file_path in file_paths:
  18. if os.path.exists(file_path):
  19. # 将文件添加到zip中,保持相对路径结构
  20. arcname = os.path.basename(file_path)
  21. zipf.write(file_path, arcname)
  22. else:
  23. raise FileNotFoundError(f"文件不存在: {file_path}")
  24. if delete_after_zip:
  25. for file_path in file_paths:
  26. os.remove(file_path)
  27. return True
  28. except Exception as e:
  29. print(f"压缩文件失败: {e}")
  30. return False
  31. def unzip_files(zip_path: str, output_dir: str) -> bool:
  32. """
  33. 解压缩zip文件到指定目录
  34. Args:
  35. zip_path: 要解压的zip文件路径
  36. output_dir: 解压输出目录
  37. Returns:
  38. bool: True表示解压成功,False表示失败
  39. """
  40. try:
  41. # 确保输出目录存在
  42. os.makedirs(output_dir, exist_ok=True)
  43. with zipfile.ZipFile(zip_path, 'r') as zipf:
  44. zipf.extractall(output_dir)
  45. return True
  46. except Exception as e:
  47. print(f"解压文件失败: {e}")
  48. return False