patool
patool is a portable archive file manager that supports a wide array of formats like 7z, RAR, ZIP, and TAR. It simplifies archive handling by abstracting away the complexities of various underlying compression programs. While it can natively handle formats like TAR, ZIP, BZIP2, LZMA, and GZIP, it often relies on helper applications installed on the system for other formats. The library is actively maintained, with frequent releases, and is currently at version 4.0.4, requiring Python 3.11 or later.
Warnings
- breaking Version 4.0.0 introduced a change in behavior when a program does not support a compression type; patool now tries to find other programs instead of failing. This primarily affects users relying on unofficial API usage that might have expected the previous failure mode.
- gotcha For many archive formats (e.g., RAR, 7z, XZ), `patool` relies on external command-line tools to be installed on the system (e.g., `unrar`, `7z`, `xz`, `tar`). Without these helper applications in the system's PATH, `patool` will raise a `PatoolError` for those formats.
- gotcha The correct way to import the library for programmatic use is `import patoolib`. Importing `patool` directly (e.g., `import patool`) will result in an `ImportError` or `ModuleNotFoundError`.
- gotcha By default, `patoolib` functions like `extract_archive` are `interactive` (True). This means they might wait for user input if the underlying compression program requires it (e.g., for a password). In automated scripts, this can lead to indefinite hangs.
- gotcha While `patool` requires Python >= 3.11, some advanced features or native support for certain formats may depend on newer Python versions. For instance, native support for the ZSTANDARD archive format is enabled with Python >= 3.14.
Install
-
pip install patool -
pip install 'patool[argcompletion]'
Imports
- patoolib
import patoolib
Quickstart
import patoolib
import os
# Create a dummy file for archiving
dummy_file_path = 'my_document.txt'
with open(dummy_file_path, 'w') as f:
f.write('This is a test document for patool.\n')
f.write('It contains some arbitrary text.')
archive_name = 'my_archive.zip'
extract_dir = 'extracted_content'
print(f"Creating archive: {archive_name}")
patoolib.create_archive(archive_name, (dummy_file_path,))
print(f"Extracting archive '{archive_name}' to '{extract_dir}'")
os.makedirs(extract_dir, exist_ok=True)
patoolib.extract_archive(archive_name, outdir=extract_dir)
print(f"Contents of '{extract_dir}':")
for root, dirs, files in os.walk(extract_dir):
for name in files:
print(os.path.join(root, name))
# Clean up dummy files and directory
os.remove(dummy_file_path)
os.remove(archive_name)
os.remove(os.path.join(extract_dir, dummy_file_path))
os.rmdir(extract_dir)
print("Cleaned up.")