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

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

问题描述

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

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

推荐答案

正如其他人指出的那样,您应该使用

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:

#!/usr/bin/env python
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))

if __name__ == '__main__':
    zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)
    zipdir('tmp/', zipf)
    zipf.close()

改编自: http://www.devshed.com/c/a/Python/Python-UnZipped/

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

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