Last modified: Feb 10, 2026 By Alexander Williams

Python Extract Zip File: A Complete Guide

Working with compressed files is a common task. Python makes it simple. The built-in zipfile module provides all the tools you need. This guide will show you how to extract zip files efficiently.

You will learn the basics first. Then we will explore more advanced options. These include handling passwords and extracting specific files. By the end, you will be confident in managing zip archives with Python.

Understanding the Zipfile Module

Python's zipfile module is part of the standard library. You do not need to install anything. It allows you to create, read, write, and extract ZIP archives. For a broader look at archive handling, see our guide on Python Zip Files: Create, Read, Extract Archives.

The module centers around the ZipFile class. You use it to open and interact with a zip file. It supports different modes like read ('r') and write ('w').

Basic Zip File Extraction

Let's start with a simple example. We will extract all files from an archive to a directory.


import zipfile

# Define the path to your zip file and target directory
zip_path = 'example_archive.zip'
extract_dir = 'extracted_files'

# Open the zip file in read mode
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
    # Extract all contents to the target directory
    zip_ref.extractall(extract_dir)

print(f"All files extracted to '{extract_dir}'.")
    

The with statement ensures the file is properly closed. The extractall() method does the heavy lifting. It creates the target folder if it doesn't exist.

Extracting Specific Files from a Zip

Sometimes you only need one file. Extracting everything is wasteful. You can use the extract() method for this.


import zipfile

zip_path = 'data_archive.zip'

with zipfile.ZipFile(zip_path, 'r') as zip_ref:
    # List all files in the archive
    file_list = zip_ref.namelist()
    print("Files in archive:", file_list)

    # Extract only 'report.txt'
    zip_ref.extract('report.txt', path='important_data')

print("Specific file extracted successfully.")
    

Files in archive: ['report.txt', 'data.csv', 'image.png']
Specific file extracted successfully.
    

First, namelist() shows the archive's contents. Then extract() pulls out the file you specify. The path argument controls the output location.

Handling Password-Protected Zip Files

Many archives are secured with a password. The zipfile module can handle these too. You provide the password when opening the file or during extraction.


import zipfile

zip_path = 'secure_backup.zip'
password = b'MySecret123'  # Password must be bytes

try:
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        # Set the password for the archive
        zip_ref.setpassword(password)
        zip_ref.extractall('decrypted_files')
    print("Protected archive extracted.")
except RuntimeError as e:
    print(f"Extraction failed. Wrong password? Error: {e}")
    

Note that the password must be a bytes object. Use the .setpassword() method. A wrong password will raise a RuntimeError.

Inspecting Zip File Contents

Before extracting, you might want to inspect the archive. The ZipFile.infolist() method gives detailed information.


import zipfile
from datetime import datetime

zip_path = 'project_files.zip'

with zipfile.ZipFile(zip_path, 'r') as zip_ref:
    for file_info in zip_ref.infolist():
        # Convert date_time to a readable format
        date_str = datetime(*file_info.date_time).strftime('%Y-%m-%d %H:%M')
        print(f"Filename: {file_info.filename}")
        print(f"  - File Size: {file_info.file_size} bytes")
        print(f"  - Compressed Size: {file_info.compress_size} bytes")
        print(f"  - Modified: {date_str}")
        print("-" * 30)
    

This is useful for logging or conditional extraction. You can check file sizes and dates without writing anything to disk.

Common Errors and Solutions

You might encounter some common errors. Here is how to fix them.

FileNotFoundError: This means Python cannot find your zip file. Double-check the path is correct.

BadZipFile Error: The file is corrupted or not a valid zip archive. Verify the file's integrity.

Large File Handling: For very large archives, extract files one by one. This avoids high memory usage. Use a loop with the extract() method.

Conclusion

Extracting zip files in Python is straightforward. The zipfile module is powerful and versatile. You learned to extract all files or just specific ones. You also saw how to handle password protection.

Remember to use the with statement for safe file handling. Always inspect archives before extraction when possible. This prevents errors and saves time.

For related Python techniques, explore our articles on the Python Zip Function: Iterate Over Lists and the Python Zip Function Guide: Iterate in Parallel. These cover different uses of the term "zip" in Python. Now you can efficiently manage compressed data in your projects.