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

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

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

25条回答
  •  一整个雨季
    2020-11-22 07:49

    For a concise way to retain the folder hierarchy under the parent directory to be archived:

    import glob
    import zipfile
    
    with zipfile.ZipFile(fp_zip, "w", zipfile.ZIP_DEFLATED) as zipf:
        for fp in glob(os.path.join(parent, "**/*")):
            base = os.path.commonpath([parent, fp])
            zipf.write(fp, arcname=fp.replace(base, ""))
    

    If you want, you could change this to use pathlib for file globbing.

提交回复
热议问题