Python Wrappers for 7-Zip Operations

Yes, there are several Python libraries and wrappers available for executing 7-Zip operations programmatically. Depending on whether you require a pure Python implementation or a wrapper around the native 7-Zip executable or shared libraries, you can choose from modern solutions like py7zr, libarchive-c, or generic archive wrappers like patool.

py7zr is currently the most popular, active, and fully featured Python library for working with 7z archives. Unlike traditional wrappers that require the native 7-Zip binary installed on your operating system, py7zr is written in pure Python.

It supports compression, extraction, archive inspection, multi-threading, and AES encryption.

Installation:

pip install py7zr

Extracting an Archive:

import py7zr

with py7zr.SevenZipFile('archive.7z', mode='r') as z:
    z.extractall(path='/path/to/extract')

Creating an Archive:

import py7zr

with py7zr.SevenZipFile('output.7z', mode='w') as z:
    z.writeall('/path/to/folder', 'folder_inside_archive')

2. patool

patool is a command-line wrapper that coordinates with existing system archivers, including native 7-Zip (7z or 7za). If you need the exact performance and specialized codec support of the native 7-Zip binary, patool manages the shell commands under the hood while providing a unified Python API.

Installation:

pip install patool

Usage:

import patoolib

# Extract an archive
patoolib.extract_archive("archive.7z", outdir="/path/to/extract")

# Create an archive
patoolib.create_archive("output.7z", ("file1.txt", "file2.txt"))

3. libarchive-c

libarchive-c provides Python bindings to the C library libarchive, which natively supports reading and writing 7z archives alongside ZIP, TAR, and RAR formats. It is suited for applications already relying on C-level archive handling.

Installation:

pip install libarchive-c

Extracting an Archive:

import libarchive.public

libarchive.public.extract_file('archive.7z')

4. Direct Subprocess Execution

If you need advanced 7-Zip parameters (such as custom dictionary sizes, solid block limits, or multi-volume splitting) that are not exposed by Python libraries, using Python's standard subprocess module to call the native 7z binary directly is often the most reliable method:

import subprocess

# Extract an archive with password protection
subprocess.run(['7z', 'x', 'archive.7z', '-o/path/to/extract', '-pSecretPassword', '-y'], check=True)

Summary

For most programmatic tasks requiring no external dependencies, py7zr is the standard and best-supported choice. If maximum compression speed or advanced CLI flags are necessary, driving the official 7-Zip executable via subprocess or patool provides full access to native engine capabilities.