Pure python 7-zip library providing comprehensive 7z archive format support with compression, decompression, encryption and CLI tools
—
Primary archive manipulation functionality for reading, writing, extracting, and testing 7z archives. The SevenZipFile class provides the main interface with support for password protection, selective extraction, compression configuration, and various archive modes.
Main class for interacting with 7z archives, supporting both reading and writing operations with context manager protocol.
class SevenZipFile:
def __init__(self, file, mode="r", *, filters=None, dereference=False,
password=None, header_encryption=False, blocksize=None, mp=False):
"""
Open a 7z archive file.
Parameters:
- file: str or file-like object, path to archive or file object
- mode: str, open mode ('r', 'w', 'x', 'a')
- filters: list, compression filter configuration
- dereference: bool, follow symbolic links when archiving
- password: str, password for encrypted archives
- header_encryption: bool, encrypt archive headers
- blocksize: int, compression block size
- mp: bool, enable multiprocessing (experimental)
"""Supported Modes:
'r': Read mode for extracting archives'w': Write mode for creating new archives'x': Exclusive create mode (fails if file exists)'a': Append mode for adding files to existing archivesExtract files from 7z archives with support for selective extraction, password protection, and custom output paths.
def extractall(self, path=None, *, callback=None, factory=None):
"""
Extract all members from the archive.
Parameters:
- path: str, directory to extract to (default: current directory)
- callback: ExtractCallback, progress reporting callback
- factory: WriterFactory, custom I/O factory for extraction
Returns:
None
"""
def extract(self, path=None, targets=None, recursive=False, *, callback=None, factory=None):
"""
Extract specific members from the archive.
Parameters:
- path: str, directory to extract to (default: current directory)
- targets: Collection[str], specific member names to extract
- recursive: bool, recursively extract directory contents
- callback: ExtractCallback, progress reporting callback
- factory: WriterFactory, custom I/O factory for extraction
Returns:
None
"""
def getnames(self) -> list:
"""
Get list of member names in the archive.
Returns:
List of member filenames as strings
"""
def namelist(self) -> list:
"""
Alias for getnames().
Returns:
List of member filenames as strings
"""
def getinfo(self, name) -> 'FileInfo':
"""
Get FileInfo object for a specific member.
Parameters:
- name: str, member name
Returns:
FileInfo object with member metadata
"""
def list(self) -> list:
"""
Get list of FileInfo objects for all members.
Returns:
List of FileInfo objects
"""import py7zr
# Extract all files
with py7zr.SevenZipFile('archive.7z', 'r') as archive:
archive.extractall('/tmp/output')
# Extract specific files
with py7zr.SevenZipFile('archive.7z', 'r') as archive:
files = ['readme.txt', 'docs/manual.pdf']
archive.extract(path='/tmp/output', targets=files)
# Extract with callback for progress
def progress_callback(archive_file):
print(f"Extracting: {archive_file.filename}")
with py7zr.SevenZipFile('archive.7z', 'r') as archive:
archive.extractall(callback=progress_callback)
# Get archive contents info
with py7zr.SevenZipFile('archive.7z', 'r') as archive:
file_list = archive.getnames()
for filename in file_list:
info = archive.getinfo(filename)
print(f"{filename}: {info.file_size} bytes")Create 7z archives with files and directories, supporting compression configuration, encryption, and various output modes.
def writeall(self, path, arcname=None):
"""
Add entire directory tree to archive.
Parameters:
- path: str, directory path to add
- arcname: str, archive name for directory (default: basename of path)
Returns:
None
"""
def write(self, file, arcname=None):
"""
Add single file to archive.
Parameters:
- file: str, file path to add
- arcname: str, name in archive (default: filename)
Returns:
None
"""
def writef(self, bio, arcname):
"""
Write data from file-like object to archive.
Parameters:
- bio: file-like object, data source
- arcname: str, name in archive
Returns:
None
"""
def writestr(self, data, arcname):
"""
Write string or bytes data to archive.
Parameters:
- data: str or bytes, data to write
- arcname: str, name in archive
Returns:
None
"""# Custom compression filters
lzma2_filters = [{"id": py7zr.FILTER_LZMA2, "preset": 9}]
zstd_filters = [{"id": py7zr.FILTER_ZSTD}]
multi_filters = [
{"id": py7zr.FILTER_X86},
{"id": py7zr.FILTER_LZMA2, "preset": 7}
]
# Create archive with custom compression
with py7zr.SevenZipFile('output.7z', 'w', filters=lzma2_filters) as archive:
archive.writeall('/path/to/directory')import py7zr
# Create archive from directory
with py7zr.SevenZipFile('backup.7z', 'w') as archive:
archive.writeall('/home/user/documents', 'documents')
# Add individual files
with py7zr.SevenZipFile('files.7z', 'w') as archive:
archive.write('/path/to/file1.txt', 'file1.txt')
archive.write('/path/to/file2.txt', 'renamed_file2.txt')
# Create encrypted archive
with py7zr.SevenZipFile('secure.7z', 'w', password='my_password') as archive:
archive.writeall('/sensitive/data')
# Write string data directly
with py7zr.SevenZipFile('data.7z', 'w') as archive:
archive.writestr("Hello, World!", "greeting.txt")
archive.writestr(b"\\x00\\x01\\x02", "binary_data.bin")Verify archive integrity and test extraction without writing files to disk.
def test(self):
"""
Test archive integrity by attempting decompression.
Returns:
None (raises exception on failure)
Raises:
Bad7zFile: if archive is corrupted
DecompressionError: if decompression fails
PasswordRequired: if password needed
"""
def testzip(self) -> Optional[str]:
"""
Test archive and return first bad file name.
Returns:
Optional[str]: name of first bad file, or None if all files are good
"""import py7zr
# Test archive integrity
try:
with py7zr.SevenZipFile('archive.7z', 'r') as archive:
archive.test()
print("Archive is valid")
except py7zr.Bad7zFile:
print("Archive is corrupted")
# Test and get bad file info
with py7zr.SevenZipFile('archive.7z', 'r') as archive:
bad_file = archive.testzip()
if bad_file:
print(f"Corrupted file: {bad_file}")
else:
print("All files are good")Access archive metadata and file information.
def archiveinfo(self) -> 'ArchiveInfo':
"""
Get archive metadata information.
Returns:
ArchiveInfo object with archive details
"""
def needs_password(self) -> bool:
"""
Check if archive requires password.
Returns:
bool: True if password required
"""
@property
def files(self) -> 'ArchiveFileList':
"""
Get list of files in archive.
Returns:
ArchiveFileList containing ArchiveFile objects
"""
@property
def password_protected(self) -> bool:
"""
Check if archive is password protected.
Returns:
bool: True if encrypted
"""Configure archive behavior and encryption settings.
def set_encoded_header_mode(self, mode: bool):
"""
Enable or disable header encoding.
Parameters:
- mode: bool, True to enable header encoding
"""
def set_encrypted_header(self, mode: bool):
"""
Enable or disable header encryption.
Parameters:
- mode: bool, True to encrypt headers
"""
def reset(self):
"""
Reset archive to beginning for re-reading.
Returns:
None
"""Container for archive-level metadata.
class ArchiveInfo:
@property
def filename(self) -> str: ...
@property
def size(self) -> int: ...
@property
def header_size(self) -> int: ...
@property
def method_names(self) -> list: ...
@property
def solid(self) -> bool: ...
@property
def blocks(self) -> int: ...
@property
def uncompressed(self) -> int: ...Container for individual file metadata.
class FileInfo:
@property
def filename(self) -> str: ...
@property
def file_size(self) -> int: ...
@property
def compressed_size(self) -> int: ...
@property
def header_size(self) -> int: ...
@property
def crc(self) -> int: ...
@property
def is_dir(self) -> bool: ...Detailed file information within archives.
class ArchiveFile:
"""
Represent metadata for a single file in a 7z archive.
Contains file properties including filename, permissions, timestamps,
and type information (directory, symlink, etc.).
"""
@property
def filename(self) -> str:
"""Return filename of archive file."""
@property
def emptystream(self) -> bool:
"""True if file is empty (0-byte file), otherwise False."""
def file_properties(self) -> dict[str, Any]:
"""
Return file properties as dictionary.
Keys include: 'readonly', 'is_directory', 'posix_mode', 'archivable',
'emptystream', 'filename', 'creationtime', 'lastaccesstime',
'lastwritetime', 'attributes'
Returns:
dict: file properties and metadata
"""
def is_directory(self) -> bool:
"""True if file is a directory, otherwise False."""
def is_symlink(self) -> bool:
"""True if file is a symbolic link, otherwise False."""
@property
def is_junction(self) -> bool:
"""True if file is a junction/reparse point on Windows, otherwise False."""
@property
def is_socket(self) -> bool:
"""True if file is a socket, otherwise False."""
@property
def readonly(self) -> bool:
"""True if file is readonly, otherwise False."""
@property
def archivable(self) -> bool:
"""True if file has archive attribute set, otherwise False."""
@property
def compressed(self) -> Optional[int]:
"""Compressed size in bytes."""
@property
def uncompressed(self) -> list[int]:
"""List of uncompressed sizes."""
@property
def crc32(self) -> Optional[int]:
"""CRC32 checksum of archived file (optional)."""
@property
def lastwritetime(self) -> Optional[ArchiveTimestamp]:
"""Return last written timestamp of a file."""
@property
def posix_mode(self) -> Optional[int]:
"""POSIX file mode permissions."""Windows FILETIME timestamp representation used in archive metadata.
class ArchiveTimestamp(int):
"""
Windows FILETIME timestamp.
Represents timestamps as found in 7z archives using Windows FILETIME format.
"""
def totimestamp(self) -> float:
"""
Convert 7z FILETIME to Python timestamp.
Returns:
float: Unix timestamp
"""Container for ArchiveFile objects with iteration support.
class ArchiveFileList:
"""
Iterable container of ArchiveFile objects.
Provides indexed access and iteration over files in an archive.
"""
def __init__(self, offset: int = 0): ...
def __getitem__(self, index) -> ArchiveFile: ...
def __iter__(self) -> ArchiveFileListIterator: ...
def __len__(self) -> int: ...Install with Tessl CLI
npx tessl i tessl/pypi-py7zr