Unzip .zip Files in Python Without Errors

Published on: June 3, 2026
Reading time: 3 minutes
Compactação de arquivos ZIP usando Python

Learning how to unzip .zip files in Python without errors is one of the most practical skills for anyone starting out in programming. Imagine downloading hundreds of reports or images that need organizing automatically. Doing it manually would be exhausting. Python provides powerful native tools for handling compressed data, letting you automate repetitive tasks with just a few lines of code. This guide explores the zipfile module and best practices to ensure files are extracted safely every time.

Why use Python to extract ZIP files?

Handling compressed files is a daily task for developers — whether working with CSV files that arrive zipped from a server, or preparing an automatic backup. Python stands out because it requires no external software like WinRAR or 7-Zip. Everything is built into the standard library, making your scripts fully portable. According to the Python Software Foundation documentation, the module also supports ZIP64 extensions for files larger than 4 GB.

Step 1: Check the file exists

import zipfile
import os
from pathlib import Path

zip_path = "data.zip"

if os.path.exists(zip_path):
    print("File found. Starting extraction...")
else:
    print("Error: The specified file does not exist.")

Step 2: Open and extract

The safest way is the with context manager — it guarantees the file closes properly even if an error occurs:

with zipfile.ZipFile(zip_path, 'r') as zf:
    zf.extractall("output_folder")
    print("Files extracted successfully!")

Step 3: Test integrity before extracting

Not every file ending in .zip is valid. The testzip() method verifies checksums on all internal files. It returns None if everything is healthy:

try:
    with zipfile.ZipFile(zip_path, 'r') as zf:
        bad = zf.testzip()
        if bad:
            print(f"Corrupted file detected: {bad}")
        else:
            zf.extractall("safe_output")
except zipfile.BadZipFile:
    print("Error: The file is not a valid ZIP.")

Extracting a specific file only

If you only need one file from a large archive, extract() avoids wasting time on everything else:

with zipfile.ZipFile("package.zip", 'r') as zf:
    file_list = zf.namelist()

    if "report.csv" in file_list:
        zf.extract("report.csv", "specific_folder")
        print("Individual file extracted.")

Complete project script

import zipfile
from pathlib import Path

def safe_unzip(zip_file, output_folder):
    """Unzip a ZIP archive with built-in error checks."""
    zip_path = Path(zip_file)
    output_path = Path(output_folder)

    if not zip_path.is_file():
        print(f"Error: '{zip_file}' not found.")
        return

    try:
        with zipfile.ZipFile(zip_path, 'r') as zf:
            bad = zf.testzip()
            if bad is not None:
                print(f"Warning: '{bad}' inside the ZIP appears corrupted.")

            output_path.mkdir(parents=True, exist_ok=True)

            print(f"Extracting to '{output_folder}'...")
            zf.extractall(output_path)
            print("Done!")

    except zipfile.BadZipFile:
        print("Critical error: file is not a valid or readable ZIP.")
    except PermissionError:
        print("Error: no write permission to the destination folder.")
    except Exception as e:
        print(f"Unexpected error: {e}")

if __name__ == "__main__":
    safe_unzip("my_project.zip", "extracted_files")

Security note: Zip Slip attacks

Never extract files from unknown sources without caution. A known attack called “Zip Slip” embeds paths like ../../etc/passwd inside the ZIP, attempting to overwrite sensitive system files during extraction. Modern Python has basic protections, but it is good practice to call namelist() and inspect the contents before running extractall() on untrusted archives.

Frequently Asked Questions

How do I unzip a password-protected ZIP?

extractall() accepts a pwd argument: zf.extractall(pwd=b'mypassword'). Note that the classic ZIP encryption supported by the module is not particularly strong.

Can Python extract .rar or .7z files?

Not natively. The zipfile module supports only the ZIP standard. For .rar use the rarfile third-party library; for .7z use py7zr.

How do I list the contents without extracting?

Use zf.printdir() for a formatted terminal table, or zf.infolist() for objects with details like original size, compressed size, and modification date.

How do I extract a file into memory without saving to disk?

Use zf.read('filename'). It returns the content as bytes, letting you process data directly in RAM — useful for performance-sensitive pipelines.

Why do I get a BadZipFile error?

The file header does not match the ZIP standard. This happens when a download was interrupted, a file was incorrectly renamed from another extension, or the archive is genuinely corrupted.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    representação de automação com ícones de engrenagens, gráficos e pessoas no background
    Automation and Scripts
    Foto de perfil de Leandro Hirt da Academify

    Automate Everyday Tasks with Python

    Learn how to automate everyday tasks with Python: organize files, rename batches, process CSV data, create reports, schedule scripts, and

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    logo do BeautifulSoup em um fundo branco
    Automation and Scripts
    Foto de perfil de Leandro Hirt da Academify

    Web Scraping with BeautifulSoup and Requests

    Learn web scraping with Requests and BeautifulSoup: fetch pages, parse HTML, select elements, clean data, follow pagination, handle errors, respect

    Ler mais

    Tempo de leitura: 6 minutos
    10/07/2026
    Criação de bot Telegram com Python
    Automation and Scripts
    Foto de perfil de Leandro Hirt da Academify

    Build a Telegram Bot with Python

    Build a Telegram bot with Python step by step: create a bot token, handle commands and messages, add buttons, store

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Automação web com Selenium usando Python
    Automation and ScriptsWeb Development
    Foto de perfil de Leandro Hirt da Academify

    Selenium with Python: Complete Web Automation Guide

    Learn Selenium with Python from setup to browser control, element locators, waits, forms, screenshots, page objects, testing, and reliable web

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Geração de arquivos PDF usando biblioteca FPDF em Python
    Automation and Scripts
    Foto de perfil de Leandro Hirt da Academify

    Create PDF Files with Python and FPDF

    Learn to create PDF files with Python and fpdf2: pages, fonts, paragraphs, images, tables, headers, footers, Unicode, invoices, paths, and

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    Logos do Python e Excel lado a lado representando a importação de dados do Excel para Python.
    Automation and Scripts
    Foto de perfil de Leandro Hirt da Academify

    Import Excel Data into Python with Pandas

    Learn how to import Excel data into Python with Pandas and openpyxl, select sheets and columns, clean values, handle dates

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026