Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

How to Automatically Extract Every Archive in a Folder with Python

Walk through a folder and extract all ZIP, RAR, and 7Z archives into separate subdirectories using Python.

Medium Python 3.9+ Jun 28, 2026 Files & data 2 views 0 copies

Requires third-party packages — install first
pip install rarfile py7zr

Python code

31 lines
Python 3.9+
import zipfile
import rarfile
import py7zr
import pathlib

def extract_archives(folder: str):
    """Extract every ZIP, RAR, and 7Z archive in the given folder."""
    folder_path = pathlib.Path(folder)
    for archive_file in folder_path.iterdir():
        suffix = archive_file.suffix.lower()
        try:
            if suffix == ".zip":
                with zipfile.ZipFile(archive_file, 'r') as zf:
                    zf.extractall(path=folder_path / archive_file.stem)
                print(f"Extracted {archive_file.name}")
            elif suffix == ".rar":
                with rarfile.RarFile(archive_file, 'r') as rf:
                    rf.extractall(path=folder_path / archive_file.stem)
                print(f"Extracted {archive_file.name}")
            elif suffix == ".7z":
                with py7zr.SevenZipFile(archive_file, 'r') as sz:
                    sz.extractall(path=folder_path / archive_file.stem)
                print(f"Extracted {archive_file.name}")
        except Exception as e:
            print(f"Failed to extract {archive_file.name}: {e}")

if __name__ == "__main__":
    # Example usage: extract archives from the current directory
    import sys
    target_folder = sys.argv[1] if len(sys.argv) > 1 else "."
    extract_archives(target_folder)

Output

stdout
Extracted data.zip
Extracted notes.rar
Extracted images.7z

How it works

The script uses pathlib.Path.iterdir() to scan the folder and checks each file's suffix. For each supported archive type it opens the file with the appropriate library—zipfile.ZipFile (stdlib), rarfile.RarFile, or py7zr.SevenZipFile—and extracts all contents into a subdirectory named after the archive (without extension). A try/except block catches and reports extraction errors for individual files without stopping the whole process.

Common mistakes

  • Assuming all archives are in the folder root rather than recursing into subfolders.
  • Forgetting to handle password-protected archives (the provided code does not include password handling).
  • Not checking if the extraction target folder already exists to avoid permission errors.

Variations

  1. Use `shutil.unpack_archive()` for ZIP and TAR only (stdlib, no RAR/7Z support).
  2. Add `is_dir()` filter and recursion with `rglob('*')` to find archives in nested folders.

Real-world use cases

  • Bulk-extracting downloaded datasets that often come in multiple compressed archives.
  • Unpacking a collection of project artifacts before running a build pipeline.
  • Automating extraction of user-uploaded files in a web application backend.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Files & data

Related tutorials and quizzes for this topic.