Python – How to create a zip archive of a directory

archivedirectory-treepythonzipzipfile

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

Edit 20th of September 2021:
Please use the solution with make_archive from shutil as it is the most convenient one and has the most upvotes. The original questioner isn't registered anymore

Edit: 3rd of November 2021
Note that starting from Python 3.4 it is recommended to use Path objects instead of plain strings when working with files in Python. However, shutil.make_archive does not accept Path objects, but zipfile does.

Best Answer

The easiest way is to use shutil.make_archive. It supports both zip and tar formats.

import shutil
shutil.make_archive(output_filename, 'zip', dir_name)

If you need to do something more complicated than zipping the whole directory (such as skipping certain files), then you'll need to dig into the zipfile module as others have suggested.