How can I create a zip archive of a directory structure in Python?
How can I create a zip archive of a directory structure in Python?
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='.')
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.
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.)
If you have python3.5+, and specifically want to zip up a Python package, use zipapp:
$ python -m zipapp myapp
$ python myapp.pyz