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

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

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

25条回答
  •  一生所求
    2020-11-22 08:07

    To add the contents of mydirectory to a new zip file, including all files and subdirectories:

    import os
    import zipfile
    
    zf = zipfile.ZipFile("myzipfile.zip", "w")
    for dirname, subdirs, files in os.walk("mydirectory"):
        zf.write(dirname)
        for filename in files:
            zf.write(os.path.join(dirname, filename))
    zf.close()
    

提交回复
热议问题