当前位置:   article > 正文

Python 解压文件、压缩文件(zip,rar)_python代码zip自动解压

python代码zip自动解压

1. python 解压zip压缩包或rar压缩包

  1. import zipfile
  2. # from unrar import rarfile # python2
  3. import rarfile # python3
  4. def zip_decompress(file_path, new_path):
  5. """支持中文的解压缩程序
  6. file_path:原压缩包文件路径
  7. new_path:新文件夹路径
  8. """
  9. if file_path.split('.')[-1] == 'zip':
  10. z = zipfile.ZipFile(file_path, 'r')
  11. z.extractall(path=new_path)
  12. else:
  13. z = rarfile.RarFile(file_path, 'r')
  14. z.extractall(path=new_path)
  15. if __name__ == "__main__":
  16. file_path = r"C:\test\zip_test\Django.rar"
  17. new_path = r"C:\test\zip_test"
  18. zip_decompress(file_path, new_path)

2. python将文件/文件夹压缩为zip压缩包

  1. import os
  2. import zipfile
  3. def zipDir(dirpath, target_path):
  4. """
  5. 压缩指定文件夹
  6. :param dirpath: 目标文件夹路径
  7. :param target_path: 压缩文件保存路径
  8. """
  9. pre_len = len(os.path.dirname(target_path))
  10. zip = zipfile.ZipFile(target_path, "w", zipfile.ZIP_DEFLATED)
  11. for path, dirnames, filenames in os.walk(dirpath):
  12. # # 1.去掉目标跟路径,只对目标文件夹下边的文件及文件夹进行压缩
  13. # fpath = path.replace(dirpath, '')
  14. # for filename in filenames:
  15. # pathfile = os.path.join(path, filename)
  16. # arcname = os.path.join(fpath, filename) # 归档文件
  17. # zip.write(pathfile, arcname)
  18. # 2. 带文件夹压缩
  19. for filename in filenames:
  20. pathfile = os.path.join(path, filename)
  21. arcname = pathfile[pre_len:].strip(os.path.sep) # 相对路径
  22. zip.write(pathfile, arcname)
  23. zip.close()
  24. if __name__ == "__main__":
  25. dirpath = r"C:\test\zip_test\pdfconver"
  26. target_path = r"C:\test\zip_test\pdfconver.zip"
  27. zipDir(dirpath, target_path)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/746338
推荐阅读
相关标签
  

闽ICP备14008679号