PythonPandas.com

Python – How to zip files



When you need to compress multiple files or directories into a single archive, Python makes it easy using its built-in zipfile module. Python’s standard library offers the zipfile module for this. There are also third-party modules and strategies for efficiency on large files.

In this article, you’ll learn how to create ZIP files in Python, including how to zip multiple files, zip entire folders recursively, choose compression levels, and safely handle errors.

Method 1: Using zipfile to Zip Multiple Files

import zipfile

# List of files to include in the zip
files = ['report1.txt', 'image.png', 'data.csv']

# Create a ZIP file and write each file
with zipfile.ZipFile('archive.zip', mode='w', compression=zipfile.ZIP_DEFLATED) as zf:
for file in files:
zf.write(file)

print("archive.zip created successfully!")

Output:

archive.zip created successfully!

Method 2: Zip an Entire Folder Recursively

Sometimes you want to zip all files and subfolders in a directory. You can do this easily using os.walk().

import os import zipfile

folder_path = '/path/to/my_folder'

with zipfile.ZipFile('folder_backup.zip', 'w', compression=zipfile.ZIP_DEFLATED) as zf:
for root, dirs, files in os.walk(folder_path):
for file in files:
full_path = os.path.join(root, file)
rel_path = os.path.relpath(full_path, start=folder_path)
zf.write(full_path, arcname=rel_path)

print("folder_backup.zip created successfully!")

Output:

folder_backup.zip created successfully!

Method 3: Using pathlib for Modern File Handling

from pathlib import Path import zipfile

dir_path = Path('/path/to/my_folder')

with zipfile.ZipFile('pathlib_example.zip', 'w', compression=zipfile.ZIP_DEFLATED) as zf:
for file in dir_path.rglob('*'):
if file.is_file():
zf.write(file, arcname=file.relative_to(dir_path))

print("pathlib_example.zip created successfully!")

Output:

pathlib_example.zip created successfully!

Method 4: Choose Compression Type (ZIP_STORED, ZIP_BZIP2, ZIP_LZMA)

import zipfile

# Choose compression algorithm
with zipfile.ZipFile('compressed_lzma.zip', 'w', compression=zipfile.ZIP_LZMA) as zf:
zf.write('bigfile.txt')

print("compressed_lzma.zip created successfully!")

Output:

compressed_lzma.zip created successfully!

Why use this?
> Choose higher compression for smaller ZIPs (ZIP_BZIP2 or ZIP_LZMA)
> Use ZIP_STORED for faster zipping without compression.

Method 5: Safe Zipping with Error Handling

Always handle permission errors or missing files gracefully.

import os, zipfile

folder_path = '/path/to/my_folder'

with zipfile.ZipFile('safe_backup.zip', 'w', compression=zipfile.ZIP_DEFLATED) as zf:
for root, dirs, files in os.walk(folder_path):
for fname in files:
full_path = os.path.join(root, fname)
try:
zf.write(full_path, arcname=os.path.relpath(full_path, folder_path))
except PermissionError:
print(f"Skipping {fname}: no permission")

print("safe_backup.zip created with available files.")

Output:

safe_backup.zip created with available files.

FAQs — Python: How to Zip Files

How to zip files in Python using the zipfile module?

Use Python’s built-in zipfile module to compress one or more files into a ZIP archive:

import zipfile

with zipfile.ZipFile('archive.zip', 'w') as zipf:
    zipf.write('file1.txt')
    zipf.write('file2.txt')

This creates archive.zip containing the specified files.

How to zip all files in a folder using Python?

Loop through a directory and add each file to the ZIP:

import os, zipfile

folder = 'path/to/folder'
with zipfile.ZipFile('output.zip', 'w') as zipf:
    for file in os.listdir(folder):
        zipf.write(os.path.join(folder, file), file)

This compresses all files in the folder into one ZIP file.

How to zip an entire directory (including subfolders) in Python?

Use os.walk() to traverse directories recursively:

import os, zipfile

folder = 'project'
with zipfile.ZipFile('project.zip', 'w') as zipf:
    for root, dirs, files in os.walk(folder):
        for file in files:
            path = os.path.join(root, file)
            zipf.write(path, os.path.relpath(path, folder))

This keeps your folder structure intact inside the ZIP file.

How to zip files in Python using shutil.make_archive()?

The shutil module provides a simpler way to create ZIP archives in one line:

import shutil

shutil.make_archive('backup', 'zip', 'path/to/folder')

This automatically zips the entire directory into backup.zip.

How to zip multiple specific files together in Python?

Add selected files manually to a ZIP archive:

files = ['file1.txt', 'file2.csv', 'notes.docx']

with zipfile.ZipFile('selected.zip', 'w') as zipf:
    for f in files:
        zipf.write(f)

How to password-protect a ZIP file in Python?

The built-in zipfile module doesn’t support password protection directly.
Use the pyminizip or zipfile36 library:

import pyminizip

pyminizip.compress('file.txt', None, 'secure.zip', 'mypassword', 5)

This creates a password-protected ZIP file.

How to extract or unzip files in Python?

Use the same zipfile module with extractall():

import zipfile

with zipfile.ZipFile('archive.zip', 'r') as zipf:
    zipf.extractall('output_folder')

This extracts all files from the ZIP to the specified directory.

How to check which files are inside a ZIP archive using Python?

Use ZipFile.namelist() to list all contents of a ZIP file:

with zipfile.ZipFile('archive.zip', 'r') as zipf:
    print(zipf.namelist())

This returns a list of filenames stored inside the archive.


Related Post