How to Create Zip Archive of Directory in Python
If you need to create a zip of a directory using Python, then you can do the following:
Create a Zip using shutil in Python
import os
import shutil
filename = "compressed_archive"
format = "zip"
directory = os.getcwd()
shutil.make_archive(filename, format, directory)
The shutil.make_archive function is the easiest way to zip a directory in Python — it handles the recursion and file permissions for you. I use this in backup scripts and when packaging build artifacts for deployment.
The format parameter also supports tar, gztar, and bztar if you need a different compression format. Note that the output file gets created in the current working directory by default. If you need more control — like excluding certain files or setting compression levels — use the zipfile module directly instead.