Python zipfile recursive write
This function recursively zips files in directories, storing only the relative path due to the use of the “arcname” parameter. Otherwise, you get the path relative to the root of your filesystem, which is rarely useful.
import zipfile
from pathlib import Path
import os
def zip_dirs(path: Path, pattern: str):
"""
recursively .zip a directory
"""
path = Path(path).resolve(strict=True)
dirs = (d for d in path.glob(pattern) if d.is_dir())
for d in dirs:
zip_name = d.with_suffix(".zip")
with zipfile.ZipFile(zip_name, mode="w", compression=zipfile.ZIP_LZMA) as z:
for root, _, files in os.walk(d):
for file in files:
fn = Path(root, file)
afn = fn.relative_to(path)
z.write(fn, arcname=afn)
print("write", zip_name)