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.
pip install rarfile py7zr
Python code
31 linesimport 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
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
- Use `shutil.unpack_archive()` for ZIP and TAR only (stdlib, no RAR/7Z support).
- 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
More from Files & data
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a Personal Work Hours Tracker in Python medium
- Build a Python Script That Detects and Deletes Empty Files Across Folders easy
Keep learning
Related tutorials and quizzes for this topic.