How to zip folder recursively using Python (zipfile)
This script will zip the folder myfolder recursively to myzip. Note that empty directories will not be copied over to the ZIP.
zip_folder_recursive.py
#!/usr/bin/env python3
import zipfile
import os
# This folder
folder = "myfolder"
with zipfile.ZipFile(f"{folder}.zip", "w") as outzip:
for subdir, dirs, files in os.walk(folder):
for file in files:
# Read file
srcpath = os.path.join(subdir, file)
dstpath_in_zip = os.path.relpath(srcpath, start=folder)
with open(srcpath, 'rb') as infile:
# Write to zip
outzip.writestr(dstpath_in_zip, infile.read())Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow