pyunpack: Unpack Archive Files

0.3 · active · verified Thu Apr 16

pyunpack is a Python library that provides a simple interface for unpacking various archive file formats such as ZIP, RAR, and 7z. It primarily acts as a wrapper around the `patool` library, which in turn leverages external command-line unarchiving tools. If `patool` is not available or cannot handle a specific format, `pyunpack` falls back to Python's built-in `zipfile` module for ZIP archives. The current stable version is 0.3, released in June 2022, with an infrequent release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to unpack a simple ZIP archive using `pyunpack`. It includes steps to create a dummy ZIP file, extract its contents, verify the extraction, and clean up afterwards. For non-ZIP formats, ensure `patool` and the corresponding external unarchiving utilities are installed and accessible in your system's PATH.

# First, create a dummy archive file for testing (e.g., 'test_archive.zip')
# For example, create 'hello.txt' with content 'Hello, pyunpack!' and then run:
# zip test_archive.zip hello.txt

import os
import shutil
from pyunpack import Archive

# Ensure a dummy archive exists and a target directory
archive_name = 'test_archive.zip'
extract_dir = 'extracted_files'

# Clean up previous runs if any
if os.path.exists(extract_dir):
    shutil.rmtree(extract_dir)
if os.path.exists(archive_name):
    os.remove(archive_name)

# Create a dummy file and zip it
with open('hello.txt', 'w') as f:
    f.write('Hello, pyunpack!\n')
import zipfile
with zipfile.ZipFile(archive_name, 'w') as zf:
    zf.write('hello.txt')
os.remove('hello.txt') # Clean up dummy source file

# Perform the extraction
try:
    print(f"Extracting '{archive_name}' to '{extract_dir}'...")
    Archive(archive_name).extractall(extract_dir)
    print("Extraction successful!")

    # Verify content
    extracted_file_path = os.path.join(extract_dir, 'hello.txt')
    if os.path.exists(extracted_file_path):
        with open(extracted_file_path, 'r') as f:
            content = f.read().strip()
        print(f"Content of extracted file: '{content}'")
    else:
        print("Error: Extracted file 'hello.txt' not found.")

except Exception as e:
    print(f"An error occurred: {e}")
finally:
    # Clean up created files and directory
    if os.path.exists(archive_name):
        os.remove(archive_name)
    if os.path.exists(extract_dir):
        shutil.rmtree(extract_dir)

view raw JSON →