How to create a zip file using Python?

ZIP is a widely used file format that compresses one or more files into a single archive file. This file format helps to reduce storage space and simplifies sharing or save backup of large data files. ZIP archives usually have a .zip file extension and are commonly used across different platforms.

Compressed ZIP files reduce the size of the original directory by applying a compression algorithm. This results in faster file sharing over a network as the size of the ZIP file is significantly smaller than the original file.

Python Modules for Creating ZIP Files

In Python, we have two standard modules for creating ZIP files ?

  • zipfile: The Python ZIP module provides various methods to compress and decompress files. It supports multiple compression algorithms, DEFLATE being the most common. Using this module we can create, read, write, append, and list a ZIP file.
  • shutil: The Python Shutil module provides methods to perform various high-level operations on files and collections of files.

Using shutil.make_archive() Method

The shutil.make_archive() method provides a quick and easy way to archive a complete folder. The make_archive() function handles both archiving and compression in a single step.

Example

Following is an example that compresses a folder into a ZIP file using the shutil.make_archive() method ?

import shutil
import os

# Create a sample directory with files
os.makedirs("sample_folder", exist_ok=True)
with open("sample_folder/file1.txt", "w") as f:
    f.write("This is file 1")
with open("sample_folder/file2.txt", "w") as f:
    f.write("This is file 2")

# Compress the entire folder into a ZIP file
archive_name = shutil.make_archive("my_archive", "zip", "sample_folder")
print(f"Archive created: {archive_name}")
Archive created: my_archive.zip

Using zipfile.ZipFile() Method

The zipfile.ZipFile() method is useful when we want to add specific files or customize the ZIP file creation. We can also apply compression for a smaller output size with this method.

Creating ZIP from Multiple Files

Following is an example that shows how to include multiple individual files into a ZIP file ?

from zipfile import ZipFile

# Create sample files
with open("sample1.txt", "w") as f:
    f.write("Content of sample file 1")
with open("sample2.txt", "w") as f:
    f.write("Content of sample file 2")

# List of files to include in the archive
file_list = ["sample1.txt", "sample2.txt"]

# Create ZIP file and write files into it
with ZipFile("output.zip", "w") as zipf:
    for file in file_list:
        zipf.write(file)

print("ZIP file 'output.zip' created successfully")
ZIP file 'output.zip' created successfully

Creating a Compressed ZIP File

To compress files within the ZIP, we use the ZIP_DEFLATED mode in the ZipFile() method, which reduces the archive size ?

from zipfile import ZipFile, ZIP_DEFLATED

# Create sample files
with open("data1.txt", "w") as f:
    f.write("This is a large text file with lots of content to demonstrate compression.")
with open("data2.txt", "w") as f:
    f.write("Another file with repetitive content for compression testing.")

# Create a compressed ZIP file
with ZipFile("compressed.zip", "w", compression=ZIP_DEFLATED) as zipf:
    zipf.write("data1.txt")
    zipf.write("data2.txt")

print("Compressed ZIP file created")
Compressed ZIP file created

Creating ZIP File from an Entire Directory

To zip all files in a folder including all sub-folders, we use the os.walk() method to traverse the directory and add each file to the archive manually ?

import os
from zipfile import ZipFile, ZIP_DEFLATED

# Create sample directory structure
os.makedirs("project_data/subfolder", exist_ok=True)
with open("project_data/main.py", "w") as f:
    f.write("print('Main file')")
with open("project_data/config.txt", "w") as f:
    f.write("Configuration data")
with open("project_data/subfolder/helper.py", "w") as f:
    f.write("print('Helper file')")

def create_zip_from_folder(folder_path, zip_name):
    with ZipFile(zip_name, "w", ZIP_DEFLATED) as zipf:
        for root, dirs, files in os.walk(folder_path):
            for file in files:
                file_path = os.path.join(root, file)
                zipf.write(file_path, os.path.relpath(file_path, start=folder_path))

# Compress the folder into a ZIP file
create_zip_from_folder("project_data", "backup.zip")
print("Directory compressed into backup.zip")
Directory compressed into backup.zip

Comparison of Methods

Method Best For Compression Customization
shutil.make_archive() Entire directories Default Limited
zipfile.ZipFile() Specific files Customizable Full control

Conclusion

Use shutil.make_archive() for quick directory compression and zipfile.ZipFile() for fine-grained control over file selection and compression. The zipfile module offers more flexibility for custom ZIP creation needs.

Updated on: 2026-03-24T18:41:53+05:30

72K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements