Python Script to Compress a Directory into a ZIP Archive
This concise tutorial shows how to use Python's built‑in zipfile module to recursively collect all files from a specified folder and create a compressed ZIP archive, including example code and a brief note on where to find more automation resources.
This short tutorial demonstrates how to create a zip archive of a specified folder using Python's built‑in zipfile module.
The zip_dir function first builds a list of all files in the target directory (handling both single files and nested directories), then iterates over the list, printing each relative path and adding it to a new zip file opened in write mode with compression.
import os, os.path
import zipfile
def zip_dir(dirname, zipfilename):
filelist = []
if os.path.isfile(dirname):
filelist.append(dirname)
else:
for root, dirs, files in os.walk(dirname):
for name in files:
filelist.append(os.path.join(root, name))
zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
for tar in filelist:
arcname = tar[len(dirname):]
print(arcname)
zf.write(tar, arcname)
zf.close()
zip_dir('/xxxxxx/docs', '20180504.zip')Finally, the article ends with a brief invitation to follow a public account for more automation learning materials.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
