Fundamentals 2 min read

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.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Script to Compress a Directory into a ZIP Archive

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ScriptingFile Compressionzip
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.