unzip.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. # -*- coding: utf-8 -*-
  2. # @Time : 2024/5/17
  3. # @Author : 魏志亮
  4. import os
  5. from utils.log.trans_log import trans_print, logger
  6. import zipfile
  7. def unzip(zip_filepath, dest_path):
  8. # 解压zip文件
  9. is_success = True
  10. trans_print('开始读取文件:', zip_filepath)
  11. try:
  12. with zipfile.ZipFile(zip_filepath, 'r') as zip_ref:
  13. zip_ref.extractall(dest_path)
  14. except zipfile.BadZipFile as e:
  15. logger.exception(e)
  16. is_success = False
  17. message = str(e)
  18. trans_print('不是zip文件:', zip_filepath)
  19. return is_success, e
  20. # 遍历解压后的文件
  21. if is_success:
  22. for root, dirs, files in os.walk(dest_path):
  23. for file in files:
  24. file_path = os.path.join(root, file)
  25. # 检查文件是否是zip文件
  26. if file_path.endswith('.zip'):
  27. # 如果是,递归解压
  28. unzip(file_path, dest_path + os.sep + str(file).split(".")[0])
  29. # 删除已解压的zip文件(可选)
  30. os.remove(file_path)
  31. return is_success, ''
  32. if __name__ == '__main__':
  33. unzip(r'C:\Users\Administrator\Desktop\test.zip', r'C:\Users\Administrator\Desktop\test')