Py7zr - Pure Python 7-Zip Library
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
- breaking Versions of py7zr from 1.0.0 onwards require Python 3.10 or higher. Earlier versions supported Python 3.7+.
- breaking The `getInfo()` method of `SevenZipFile` now returns `FileInfo` dataclass objects instead of older tuple or dictionary structures. Code expecting direct dictionary/tuple access will break.
- gotcha Prior to version 1.1.0, using `SevenZipFile` with `IO[bytes]` stream objects for reading or writing archives might have been inconsistent or caused issues. This was explicitly fixed in v1.1.0.
- gotcha In versions prior to 0.21.1, the `unpack_7zarchive` function might not have reliably closed the archive handle, potentially leading to resource leaks. This was addressed in v0.21.1.
Install
-
pip install py7zr
Imports
- SevenZipFile
from py7zr import SevenZipFile
- is_7zfile
from py7zr import is_7zfile
Quickstart
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.")