patool

4.0.4 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

This example demonstrates how to create and extract a ZIP archive programmatically using `patoolib`. It first creates a dummy text file, archives it into a .zip file, then extracts the contents to a new directory, and finally cleans up the created files and folders. Ensure you have the necessary system-level archiving tools (like `zip`/`unzip`) installed if you use formats not natively supported by patool.

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.")

view raw JSON →