Last modified: Feb 10, 2026 By Alexander Williams

Python Zip Files: Create, Read, Extract Archives

Python makes file compression easy. The zipfile module is your key tool. It lets you handle ZIP archives directly from your code.

This guide covers all the essentials. You will learn to create, read, and extract ZIP files. We will use clear examples to explain each step.

What is a ZIP File?

A ZIP file is a compressed archive. It bundles multiple files into one. This saves space and organizes data.

Python's zipfile module is part of the standard library. You do not need to install anything extra. It provides a simple interface for archive operations.

Creating a New ZIP Archive

Let's start by creating a ZIP file. Use the ZipFile class in write mode ('w'). The write() method adds files to the archive.


# Import the zipfile module
import zipfile

# Create a new ZIP file in write mode
with zipfile.ZipFile('my_archive.zip', 'w') as zipf:
    # Add a file to the archive
    zipf.write('document.txt')
    zipf.write('image.jpg')
    print("Files added to archive.")
    

Files added to archive.
    

This code creates 'my_archive.zip'. It adds 'document.txt' and 'image.jpg' to it. The with statement ensures the file is closed properly.

Reading and Listing Archive Contents

You can inspect a ZIP file without extracting it. Open it in read mode ('r'). Use the namelist() method to see what's inside.


import zipfile

# Open an existing ZIP file in read mode
with zipfile.ZipFile('my_archive.zip', 'r') as zipf:
    # Get a list of all file names in the archive
    file_list = zipf.namelist()
    print("Contents of the archive:")
    for file_name in file_list:
        print(f" - {file_name}")
    

Contents of the archive:
 - document.txt
 - image.jpg
    

The namelist() method returns a simple list. It shows all files and folders stored in the archive.

Extracting Files from a ZIP Archive

Extraction is a common task. The extractall() method pulls out all files. You can also extract a single file with extract().


import zipfile

with zipfile.ZipFile('my_archive.zip', 'r') as zipf:
    # Extract all files to the current directory
    zipf.extractall(path='extracted_files/')
    print("All files extracted.")

    # Extract a single specific file
    zipf.extract('document.txt', path='single_file/')
    print("Single file extracted.")
    

All files extracted.
Single file extracted.
    

Always specify a path for extraction. This keeps your project folder organized and clean.

Working with In-Memory Data

Sometimes you need to work with data in memory. You can create a ZIP archive from bytes without saving to disk first. This is useful for web applications.


import zipfile
import io

# Create a bytes buffer to hold the ZIP data
in_memory_zip = io.BytesIO()

# Create the ZIP file in the buffer
with zipfile.ZipFile(in_memory_zip, 'w') as zipf:
    # You can write string data directly
    zipf.writestr('note.txt', 'This is a text note inside the ZIP.')
    zipf.writestr('data.csv', 'name,age\nAlice,30\nBob,25')

# Get the bytes of the ZIP file
zip_bytes = in_memory_zip.getvalue()
print(f"Created ZIP file in memory. Size: {len(zip_bytes)} bytes")
    

Created ZIP file in memory. Size: 238 bytes
    

The writestr() method is key here. It writes a string of data directly into the archive under a given filename.

Handling Passwords and Encryption

Python can handle encrypted ZIP files. Use the setpassword() method or provide the password when opening the file. Note that standard zipfile supports traditional ZIP encryption.


import zipfile

# Creating an encrypted ZIP (requires zipfile from Python 3.6+)
with zipfile.ZipFile('secure.zip', 'w', compression=zipfile.ZIP_DEFLATED) as zipf:
    zipf.setpassword(b'mysecret')  # Password must be bytes
    zipf.write('secret_data.txt')
    print("Encrypted archive created.")

# Extracting from an encrypted ZIP
try:
    with zipfile.ZipFile('secure.zip', 'r') as zipf:
        zipf.setpassword(b'mysecret')
        zipf.extractall()
        print("Extracted from encrypted archive.")
except RuntimeError as e:
    print(f"Extraction failed: {e}")
    

Encrypted archive created.
Extracted from encrypted archive.
    

Remember, traditional ZIP encryption is not highly secure. For strong security, encrypt files before adding them to the archive.

Comparing with Python's zip() Function

Do not confuse the zipfile module with the built-in zip() function. They serve different purposes.

The zipfile module handles file compression. The zip() function combines iterables. For example, you can use zip() to Python Zip Two Lists together element-wise.

If you want to learn more about iterating, see our guide on the Python Zip Function Guide: Iterate in Parallel. Another useful resource explains how to Python Zip Function: Iterate Over Lists.

Best Practices and Common Pitfalls

Always use the with statement. It automatically closes the archive. This prevents resource leaks and file locks.

Check if a file is a valid ZIP before opening it. Use the is_zipfile() function. It returns True or False.


import zipfile

# Check if a file is a valid ZIP archive
if zipfile.is_zipfile('my_archive.zip'):
    print("This is a valid ZIP file.")
else:
    print("This is NOT a valid ZIP file.")
    

Be mindful of file paths. When adding files, use relative paths. This keeps the archive portable across different systems.

Conclusion

Python's zipfile module is powerful and straightforward. You can create, read, and extract archives with just a few lines of code.

Start by creating simple archives. Then explore advanced features like in-memory ZIPs and basic encryption. Remember to use the with statement for safe file handling.

This skill is invaluable for data packaging, backup scripts, and application deployment. Now you have the tools to manage ZIP files efficiently in your Python projects.