How to create a zip archive of a directory in Python?

后端 未结 25 2618
暗喜
暗喜 2020-11-22 07:12

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

相关标签:
25条回答
  • 2020-11-22 08:14

    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()
    

    Adapted from: http://www.devshed.com/c/a/Python/Python-UnZipped/

    0 讨论(0)
提交回复
热议问题