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.
#!/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())