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

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

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

25条回答
  •  面向向阳花
    2020-11-22 08:03

    Zip a file or a tree (a directory and its sub-directories).

    from pathlib import Path
    from zipfile import ZipFile, ZIP_DEFLATED
    
    def make_zip(tree_path, zip_path, mode='w', skip_empty_dir=False):
        with ZipFile(zip_path, mode=mode, compression=ZIP_DEFLATED) as zf:
            paths = [Path(tree_path)]
            while paths:
                p = paths.pop()
                if p.is_dir():
                    paths.extend(p.iterdir())
                    if skip_empty_dir:
                        continue
                zf.write(p)
    

    To append to an existing archive, pass mode='a', to create a fresh archive mode='w' (the default in the above). So let's say you want to bundle 3 different directory trees under the same archive.

    make_zip(path_to_tree1, path_to_arch, mode='w')
    make_zip(path_to_tree2, path_to_arch, mode='a')
    make_zip(path_to_file3, path_to_arch, mode='a')
    

提交回复
热议问题