Py7zr - Pure Python 7-Zip Library

1.1.0 · active · verified Thu Apr 09

Py7zr is a pure Python library for working with 7-Zip archives, enabling creation, extraction, and inspection of `.7z` files without requiring external binaries. The library is actively maintained with a consistent release cadence, recently moving to version 1.x, and supports modern Python versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a 7z archive with a single file and then extract its contents to a new directory. It includes basic error handling and cleanup.

import py7zr
import os

archive_name = "example.7z"
file_to_archive = "test_file.txt"

# Create a dummy file for archiving
with open(file_to_archive, "w") as f:
    f.write("This is a test file for py7zr.\n")

try:
    # Create a 7z archive
    with py7zr.SevenZipFile(archive_name, 'w') as archive:
        archive.write(file_to_archive, arcname='renamed_test_file.txt')
    print(f"Archive '{archive_name}' created with '{file_to_archive}'.")

    # Extract from the 7z archive
    extract_dir = "extracted_files"
    os.makedirs(extract_dir, exist_ok=True)

    with py7zr.SevenZipFile(archive_name, mode='r') as archive:
        archive.extractall(path=extract_dir)
    print(f"Files extracted to '{extract_dir}'.")

    # Verify extraction
    extracted_path = os.path.join(extract_dir, 'renamed_test_file.txt')
    if os.path.exists(extracted_path):
        with open(extracted_path, 'r') as f:
            content = f.read()
            print(f"Content of extracted file: {content.strip()}")
    else:
        print("Extraction verification failed.")

except Exception as e:
    print(f"An error occurred: {e}")
finally:
    # Clean up created files and directories
    if os.path.exists(file_to_archive):
        os.remove(file_to_archive)
    if os.path.exists(archive_name):
        os.remove(archive_name)
    if os.path.exists(extract_dir):
        for root, dirs, files in os.walk(extract_dir, topdown=False):
            for name in files:
                os.remove(os.path.join(root, name))
            for name in dirs:
                os.rmdir(os.path.join(root, name))
        os.rmdir(extract_dir)
    print("Cleanup complete.")

view raw JSON →