如何创建目录的 zip 存档? [英] How to create a zip archive of a directory?

查看:36
本文介绍了如何创建目录的 zip 存档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Python 中创建目录结构的 zip 存档?

How can I create a zip archive of a directory structure in Python?

修改 2021 年 9 月 20 日:
请使用带有 make_archive from shutil 的解决方案,因为它是最方便且获得最多投票的解决方案.原发问者不再注册

Edit 20th of September 2021:
Please use the solution with make_archive from shutil as it is the most convenient one and has the most upvotes. The original questioner isn't registered anymore

推荐答案

正如其他人所指出的,你应该使用 zipfile.该文档会告诉您哪些函数可用,但并未真正解释如何使用它们来压缩整个目录.我认为用一些示例代码来解释最简单:

As others have pointed out, you should use zipfile. The documentation tells you what functions are available, but doesn't really explain how you can use them to zip an entire directory. I think it's easiest to explain with some example code:

import os
import zipfile
    
def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file), 
                       os.path.relpath(os.path.join(root, file), 
                                       os.path.join(path, '..')))
      
zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('tmp/', zipf)
zipf.close()

这篇关于如何创建目录的 zip 存档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆