Python - How to zip a directory

By xngo on June 12, 2019

In Python, the easiest way to zip a directory is to use shutil.make_archive(). It supports both zip and tar formats. Here is an example showing how to zip /tmp directory.

import shutil
 
# There is no need to suffix output_filename with .zip. It will be appended automatically.
shutil.make_archive(output_filename, "zip", dir_name)
 
shutil.make_archive("my-tmp-dir", "zip", "/tmp") # my-tmp-dir.zip will be created.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.