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

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

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

25条回答
  •  既然无缘
    2020-11-22 08:06

    Here's a modern approach, using pathlib, and a context manager. Puts the files directly in the zip, rather than in a subfolder.

    def zip_dir(filename: str, dir_to_zip: pathlib.Path):
        with zipfile.ZipFile(filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
            # Use glob instead of iterdir(), to cover all subdirectories.
            for directory in dir_to_zip.glob('**'):
                for file in directory.iterdir():
                    if not file.is_file():
                        continue
                    # Strip the first component, so we don't create an uneeded subdirectory
                    # containing everything.
                    zip_path = pathlib.Path(*file.parts[1:])
                    # Use a string, since zipfile doesn't support pathlib  directly.
                    zipf.write(str(file), str(zip_path))
    

提交回复
热议问题