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

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

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

25条回答
  •  灰色年华
    2020-11-22 08:13

    Modern Python (3.6+) using the pathlib module for concise OOP-like handling of paths, and pathlib.Path.rglob() for recursive globbing. As far as I can tell, this is equivalent to George V. Reilly's answer: zips with compression, the topmost element is a directory, keeps empty dirs, uses relative paths.

    from pathlib import Path
    from zipfile import ZIP_DEFLATED, ZipFile
    
    from os import PathLike
    from typing import Union
    
    
    def zip_dir(zip_name: str, source_dir: Union[str, PathLike]):
        src_path = Path(source_dir).expanduser().resolve(strict=True)
        with ZipFile(zip_name, 'w', ZIP_DEFLATED) as zf:
            for file in src_path.rglob('*'):
                zf.write(file, file.relative_to(src_path.parent))
    

    Note: as optional type hints indicate, zip_name can't be a Path object (would be fixed in 3.6.2+).

提交回复
热议问题