API Documentation¶
py7zr — 7-Zip archive library¶
The module is built upon awesome development effort and knowledge of pylzma module and its py7zlib.py program by Joachim Bauch. Great appreciation for Joachim!
This page is generated from the docstrings of the public API exported by the
py7zr package. For tutorials see the User Guide and
Advanced usage; supported algorithms and filter chains are listed in
Compression Methods.
SevenZipFile Object¶
- class py7zr.SevenZipFile(file: IO[bytes] | str | Path, mode: str = 'r', *, filters: list[dict[str, int]] | None = None, dereference: bool = False, password: str | None = None, header_encryption: bool = False, blocksize: int | None = None, mp: bool = False, max_extract_size: int | None = None)[source]¶
Provide an interface to 7z archives for reading, writing, and extracting.
SevenZipFile supports four operation modes: read (‘r’), write (‘w’), exclusive create (‘x’), and append (‘a’). It implements the context manager protocol so that archives are properly closed after use.
- Parameters:
file – Path to the archive file or a file-like object.
mode – Operation mode: ‘r’ for reading, ‘w’ for writing, ‘x’ for exclusive creation, ‘a’ for appending.
filters – Compression filter chain configuration. When
None, default filters are used automatically.dereference – When
True, follow symbolic links and store the link target content instead of the link itself.password – Password for encrypted archives. Required when reading an encrypted archive or when writing with encryption filters.
header_encryption – When
True, encrypt the archive header to hide file names and sizes.blocksize – Internal read block size in bytes. When
None, a default size is used.mp – When
True, use multiprocessing for parallel extraction on non-encrypted archives.max_extract_size – Upper bound on the total extracted data size in bytes. When the limit is exceeded, extraction stops with an error.
Attributes
The following instance attributes are available after construction. Only
filename,modeandfilesare part of the stable public API; the others reflect implementation details and may change.- Variables:
fp – The underlying file object for the archive.
mode – The current operation mode (‘r’, ‘w’, ‘x’, or ‘a’).
filename – The path of the archive file, or
Nonewhen a file-like object was passed.files – An
ArchiveFileListcontaining the archive members.header – The parsed
Headerobject describing the archive structure, orNonefor an empty archive.sig_header – The
SignatureHeaderobject with magic number, version, and CRC information.afterheader – File position immediately after the signature header.
pack_data_start – File position where pack data begins, calculated as
afterheader + packpos. Used for all pack data positioning.password_protected –
Truewhen the archive contains encrypted content.mp –
Truewhen multiprocessing extraction is enabled.dereference –
Truewhen symbolic links are followed.max_extract_size – Maximum allowed extracted data size in bytes.
encoded_header_mode –
Truewhen the header is stored in compressed form.header_encryption –
Truewhen the header is encrypted.
Pack data positioning
The 7z format defines
PackPosin the Pack Information section as an offset from the end of the signature header to the start of pack data. The pack data start position is calculated once when reading the archive header and stored aspack_data_start:When
header.main_streamsexists, it equalsafterheader + packpos.When
header.main_streamsisNone(e.g., empty archives), it equalsafterheader.
This value is used consistently for Worker creation, file pointer positioning in
reset(),test(), andtestzip(), and source position tracking. For newly created archives,packposis always 0, sopack_data_startequalsafterheader.Limitations
Deflate64 is not available on PyPy.
Socket files stored in archives are not extracted.
When duplicate file names exist in an archive, the first member keeps its original name and subsequent duplicates receive incrementing numeric suffixes, such as
file.txt_0.Multiprocessing extraction is disabled for password-protected archives and when a file-like object is passed instead of a path.
- set_encoded_header_mode(mode: bool) None[source]¶
Select whether the header is written in compressed (encoded) form.
Only meaningful in write modes and must be called before
close(). Encoded headers are enabled by default.- Parameters:
mode –
Trueto compress the header.Falsestores a plain header and also disables header encryption.
- set_encrypted_header(mode: bool) None[source]¶
Select whether the header is encrypted, hiding member names and sizes.
Only meaningful in write modes with a password, and must be called before
close(). Equivalent to theheader_encryptionconstructor argument.- Parameters:
mode –
Trueto encrypt the header. This also enables the encoded header mode.
- getnames() list[str][source]¶
Return the names of the archive members, in archive order.
Alias of
namelist(), for compatibility withtarfile.
- namelist() list[str][source]¶
Return the names of the archive members, in archive order.
Same as
getnames(), for compatibility withzipfile.
- getinfo(name: str) FileInfo[source]¶
Return a
FileInfoobject describing the archive member name.A trailing slash in name is ignored, as in
zipfile.- Parameters:
name – The member name.
- Raises:
KeyError – If the archive has no member called name.
- archiveinfo() ArchiveInfo[source]¶
Return summary information about the whole archive.
The archive must have been opened from a file path or a multi-volume file object, because the result includes
os.stat()information.- Returns:
An
ArchiveInfoobject.
- list() list[FileInfo][source]¶
Return information about all archive members.
- Returns:
A list of
FileInfoobjects, in archive order.
- extractall(path: Any | None = None, *, callback: ExtractCallback | None = None, factory: WriterFactory | None = None) None[source]¶
Extract all members from the archive.
Modification times and permissions are restored on extracted files. Member names that would escape the target directory are rejected. An archive can be extracted only once per open; call
reset()before extracting again.- Parameters:
path – The directory to extract into. Defaults to the current working directory. Created if it does not exist.
callback – An optional
py7zr.callbacks.ExtractCallbackinstance that receives progress reports.factory – An optional
WriterFactory. When given, member data is written to objects created by the factory instead of to files, and directories are skipped. See Advanced usage.
- Raises:
PasswordRequired – If the archive is encrypted and no password was given.
DecompressionBombError – If the extracted size exceeds
max_extract_size.
- extract(path: Any | None = None, targets: Collection[str] | None = None, recursive: bool | None = False, *, callback: ExtractCallback | None = None, factory: WriterFactory | None = None) None[source]¶
Extract selected members from the archive.
Works like
extractall()but only extracts the members named in targets. An archive can be extracted only once per open; callreset()before extracting again.- Parameters:
path – The directory to extract into. Defaults to the current working directory.
targets – A collection (list or set) of member names to extract, or
Noneto extract everything. Trailing slashes are ignored. For a single member pass["name"], not a bare string.recursive – When
True, also extract every member whose name starts with one of the targets, so a directory name selects its whole subtree.callback – An optional
py7zr.callbacks.ExtractCallbackinstance that receives progress reports.factory – An optional
WriterFactory; seeextractall().
- Raises:
TypeError – If targets is not a collection or
None.
- writeall(path: Path | str, arcname: str | None = None) None[source]¶
Add a file or a whole directory tree to the archive.
- Parameters:
path – A file or directory on disk. Directories are added recursively.
arcname – The name to store path under in the archive. Defaults to path with any leading slash or drive letter removed.
- Raises:
ValueError – If path does not exist or is neither a file nor a directory.
- write(file: Path | str, arcname: str | None = None) None[source]¶
Add a single file to the archive.
Unlike
writeall(), directories are stored as a single entry without their contents.- Parameters:
file – A file on disk.
arcname – The name to store file under in the archive. Defaults to file with any leading slash or drive letter removed.
- Raises:
ValueError – If file is not a
strorpathlib.Path.
- writef(bio: IO[Any], arcname: str) None[source]¶
Add the contents of a binary file object to the archive.
- Parameters:
bio – A binary file object, such as
io.BytesIOor a file opened in'rb'mode.arcname – The member name to store the data under.
- Raises:
ValueError – If arcname is unsafe (absolute, or escaping the archive root with
..), or bio is a text-mode or unsupported object.
- writestr(data: str | bytes | bytearray | memoryview, arcname: str) None[source]¶
Add in-memory data to the archive as a member.
- Parameters:
data – The member contents. A
stris encoded as UTF-8.arcname – The member name to store the data under.
- Raises:
ValueError – If arcname is unsafe or data has an unsupported type.
- close() None[source]¶
Finish pending work and close the archive.
In write modes this compresses any buffered data and writes the archive header, so the archive is incomplete until
close()is called. Leaving awithblock calls it automatically.
- reset() None[source]¶
Rewind a read-mode archive so it can be extracted again.
Resets the file position, the extraction worker and all decompressors. Has no effect in write modes.
- test() bool | None[source]¶
Check the CRCs of the compressed (packed) streams.
This is fast because nothing is decompressed, but it only detects damage to streams that carry a stored CRC. Use
testzip()for a full check.- Returns:
Trueif all stored CRCs match,Falseif one does not, orNonewhen the archive stores no packed-stream CRCs.
- testzip() str | None[source]¶
Decompress every member and check its CRC, without writing files.
Named after
zipfile.ZipFile.testzip().- Returns:
The name of the first member with a bad CRC, or
Noneif all members are intact.
See also
Advanced usage for extracting selected members and for writing
member data to custom objects with a WriterFactory.
Information Objects¶
- class py7zr.ArchiveInfo(filename: str, stat: stat_result, header_size: int, method_names: list[str], solid: bool, blocks: int, uncompressed: int)[source]¶
Hold archive metadata returned by the
archiveinfo()method.This dataclass contains summary information about a 7z archive, including file paths, compression methods, block counts, and sizes.
- Variables:
filename – The filename of the 7z archive, or
Nonewhen the archive is opened from a file-like object.stat – The
os.stat_resultof the archive file, orNonewhen the archive is opened from a file-like object.header_size – The total size of the archive headers in bytes.
method_names – A list of compression method names used in the archive. Unsupported methods are marked with an asterisk (
*).solid –
Trueif the archive uses solid compression.blocks – The number of compression blocks in the archive.
uncompressed – The total uncompressed size of all files in the archive in bytes.
- class py7zr.FileInfo(filename: str, compressed: int | None, uncompressed: int, archivable: bool, is_directory: bool, is_file: bool, is_symlink: bool, creationtime: datetime | None, crc32: int | None)[source]¶
Hold information about one archive member.
Instances are returned by
SevenZipFile.list()andSevenZipFile.getinfo().- Variables:
filename – The member name in the archive, using
/as separator.compressed – The compressed size in bytes, or
Nonewhen the member shares a solid block with other members and its own compressed size is not known.uncompressed – The uncompressed size in bytes.
archivable –
Truewhen the archive attribute bit is set.is_directory –
Truewhen the member is a directory.is_file –
Truewhen the member is a regular file.is_symlink –
Truewhen the member is a symbolic link.creationtime – The member’s last write (modification) time as a
datetime.datetime, orNonewhen no timestamp is stored. The field name is kept for backward compatibility.crc32 – The CRC32 checksum of the uncompressed data, or
None.
At most one of
is_directory,is_fileandis_symlinkisTrue; all areFalsefor special members such as junctions or sockets.
Functions¶
- py7zr.is_7zfile(file: SupportsReadAndSeek | IO[bytes] | str | PathLike[str]) bool[source]¶
Return
Trueif file is a 7z archive, based on its magic number.- Parameters:
file – A path, or a binary file object supporting
readandseek.- Returns:
Truefor a 7z archive.Falseotherwise, including when the path does not exist.- Raises:
TypeError – If file is neither a path nor a file object.
- py7zr.unpack_7zarchive(archive, path, extra=None)[source]¶
Extract a 7z archive; a helper for
shutil.register_unpack_format().Register it once, then extract with
shutil.unpack_archive():import shutil from py7zr import unpack_7zarchive shutil.register_unpack_format("7zip", [".7z"], unpack_7zarchive) shutil.unpack_archive("archive.7z", "extract_dir")
- Parameters:
archive – Path of the archive to extract.
path – The directory to extract into.
extra – Unused; accepted for
shutilcompatibility.
Raises
shutil.ReadErrorif archive is not a 7z file.
- py7zr.pack_7zarchive(base_name, base_dir, owner=None, group=None, dry_run=None, logger=None)[source]¶
Create a 7z archive; a helper for
shutil.register_archive_format().Register it once, then create archives with
shutil.make_archive():import shutil from py7zr import pack_7zarchive shutil.register_archive_format("7zip", pack_7zarchive, description="7zip archive") shutil.make_archive("archive", "7zip", "base_dir")
- Parameters:
- Returns:
The archive file name,
base_name + ".7z".
See also
The shutil module offers a number of high-level operations on files
and collections of files.
I/O Interfaces¶
- class py7zr.Py7zIO[source]¶
Abstract binary stream that receives one extracted archive member.
Objects of this type are created by a
WriterFactorypassed asfactorytopy7zr.SevenZipFile.extract()orpy7zr.SevenZipFile.extractall(). The interface is similar totyping.BinaryIOwith an additionalsize()method.py7zr may extract members in worker threads, so implementations should be thread-safe.
- abstractmethod write(s: bytes | bytearray) int[source]¶
Receive the next chunk of the member’s data.
Called repeatedly while the member is decompressed; append s to whatever was written before.
- Returns:
The number of bytes written.
- abstractmethod read(size: int | None = None) bytes[source]¶
Return up to size bytes, or all remaining data when size is
None.
- abstractmethod seek(offset: int, whence: int = 0) int[source]¶
Change the stream position, as
io.IOBase.seek().- Returns:
The new absolute position.
- close() None[source]¶
Called by py7zr when decompression of an individual archive member completes. Override to release per-file resources or to process the just-decompressed payload before py7zr moves on to the next file. Default implementation is a no-op for backward compatibility with subclasses written before this hook existed.
- class py7zr.WriterFactory[source]¶
Abstract factory that creates a
Py7zIOobject for each extracted member.Pass an instance as
factorytopy7zr.SevenZipFile.extract()orpy7zr.SevenZipFile.extractall()to receive member data in memory or stream it elsewhere instead of writing files to disk. See Advanced usage for examples.
Exceptions¶
- exception py7zr.Bad7zFile(*args: Any, **kwargs: Any)[source]¶
Raised when a file is not a valid 7z archive or its headers are malformed.
- exception py7zr.PasswordRequired[source]¶
Raised when reading or writing an encrypted archive without a password.
- exception py7zr.UnsupportedCompressionMethodError(data: Any, message: Any)[source]¶
Exception raised for unsupported compression parameter given.
- Attributes:
data – unknown property data message – explanation of error
Constants¶
Filter IDs are used in the filters argument of SevenZipFile.
See Compression Methods for supported combinations.
Name |
Meaning |
|---|---|
|
LZMA compression |
|
LZMA2 compression |
|
BZip2 compression |
|
Deflate compression |
|
ZStandard compression |
|
PPMd compression |
|
Brotli compression |
|
No compression (store) |
|
Delta filter |
|
BCJ branch converters for executable code |
|
7zAES encryption |
|
LZMA/LZMA2 |
|
Integrity check IDs, from |