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

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

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

25条回答
  •  误落风尘
    2020-11-22 08:10

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

    In a Python script

    In Python 2.7+, shutil has a make_archive function.

    from shutil import make_archive
    make_archive(
      'zipfile_name', 
      'zip',           # the archive format - or tar, bztar, gztar 
      root_dir=None,   # root for archive - current working dir if None
      base_dir=None)   # start archiving from here - cwd if None too
    

    Here the zipped archive will be named zipfile_name.zip. If base_dir is farther down from root_dir it will exclude files not in the base_dir, but still archive the files in the parent dirs up to the root_dir.

    I did have an issue testing this on Cygwin with 2.7 - it wants a root_dir argument, for cwd:

    make_archive('zipfile_name', 'zip', root_dir='.')
    

    Using Python from the shell

    You can do this with Python from the shell also using the zipfile module:

    $ python -m zipfile -c zipname sourcedir
    

    Where zipname is the name of the destination file you want (add .zip if you want it, it won't do it automatically) and sourcedir is the path to the directory.

    Zipping up Python (or just don't want parent dir):

    If you're trying to zip up a python package with a __init__.py and __main__.py, and you don't want the parent dir, it's

    $ python -m zipfile -c zipname sourcedir/*
    

    And

    $ python zipname
    

    would run the package. (Note that you can't run subpackages as the entry point from a zipped archive.)

    Zipping a Python app:

    If you have python3.5+, and specifically want to zip up a Python package, use zipapp:

    $ python -m zipapp myapp
    $ python myapp.pyz
    

提交回复
热议问题