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, mode and files are 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 None when a file-like object was passed.

  • files – An ArchiveFileList containing the archive members.

  • header – The parsed Header object describing the archive structure, or None for an empty archive.

  • sig_header – The SignatureHeader object 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 – True when the archive contains encrypted content.

  • mp – True when multiprocessing extraction is enabled.

  • dereference – True when symbolic links are followed.

  • max_extract_size – Maximum allowed extracted data size in bytes.

  • encoded_header_mode – True when the header is stored in compressed form.

  • header_encryption – True when the header is encrypted.

Pack data positioning

The 7z format defines PackPos in 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 as pack_data_start:

  • When header.main_streams exists, it equals afterheader + packpos.

  • When header.main_streams is None (e.g., empty archives), it equals afterheader.

This value is used consistently for Worker creation, file pointer positioning in reset(), test(), and testzip(), and source position tracking. For newly created archives, packpos is always 0, so pack_data_start equals afterheader.

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 – True to compress the header. False stores 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 the header_encryption constructor argument.

Parameters:

mode – True to 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 with tarfile.

namelist() → list[str][source]

Return the names of the archive members, in archive order.

Same as getnames(), for compatibility with zipfile.

getinfo(name: str) → FileInfo[source]

Return a FileInfo object 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 ArchiveInfo object.

needs_password() → bool[source]

Return True if the archive contains encrypted content.

list() → list[FileInfo][source]

Return information about all archive members.

Returns:

A list of FileInfo objects, 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.ExtractCallback instance 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:
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; call reset() 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 None to 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.ExtractCallback instance that receives progress reports.

  • factory – An optional WriterFactory; see extractall().

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 str or pathlib.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.BytesIO or 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 str is 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 a with block 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:

True if all stored CRCs match, False if one does not, or None when 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 None if 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 None when the archive is opened from a file-like object.

  • stat – The os.stat_result of the archive file, or None when 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 – True if 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() and SevenZipFile.getinfo().

Variables:
  • filename – The member name in the archive, using / as separator.

  • compressed – The compressed size in bytes, or None when the member shares a solid block with other members and its own compressed size is not known.

  • uncompressed – The uncompressed size in bytes.

  • archivable – True when the archive attribute bit is set.

  • is_directory – True when the member is a directory.

  • is_file – True when the member is a regular file.

  • is_symlink – True when the member is a symbolic link.

  • creationtime – The member’s last write (modification) time as a datetime.datetime, or None when 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_file and is_symlink is True; all are False for special members such as junctions or sockets.

Functions

py7zr.is_7zfile(file: SupportsReadAndSeek | IO[bytes] | str | PathLike[str]) → bool[source]

Return True if file is a 7z archive, based on its magic number.

Parameters:

file – A path, or a binary file object supporting read and seek.

Returns:

True for a 7z archive. False otherwise, 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 shutil compatibility.

Raises shutil.ReadError if 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:
  • base_name – Archive path without the .7z suffix.

  • base_dir – The directory to archive.

  • owner – Unused; accepted for shutil compatibility.

  • group – Unused; accepted for shutil compatibility.

  • dry_run – When true, only return the archive name.

  • logger – An optional logger used in dry-run mode.

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 WriterFactory passed as factory to py7zr.SevenZipFile.extract() or py7zr.SevenZipFile.extractall(). The interface is similar to typing.BinaryIO with an additional size() 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.

abstractmethod flush() → None[source]

Flush buffered data, if any.

abstractmethod size() → int[source]

Return the number of bytes written so far.

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 Py7zIO object for each extracted member.

Pass an instance as factory to py7zr.SevenZipFile.extract() or py7zr.SevenZipFile.extractall() to receive member data in memory or stream it elsewhere instead of writing files to disk. See Advanced usage for examples.

abstractmethod create(filename: str) → Py7zIO[source]

Return a new Py7zIO object that will receive the member filename.

Parameters:

filename – The member’s output path, using / as separator. Directories and special files are skipped, so this is only called for regular files and symbolic links.

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

exception py7zr.DecompressionError(*args: Any, **kwargs: Any)[source]

Raised when extraction fails, for example when a directory cannot be created.

exception py7zr.DecompressionBombError(*args: Any, **kwargs: Any)[source]

Exception raised when decompressed size exceeds the configured limit.

Constants

Filter IDs are used in the filters argument of SevenZipFile. See Compression Methods for supported combinations.

Name

Meaning

FILTER_LZMA

LZMA compression

FILTER_LZMA2

LZMA2 compression

FILTER_BZIP2

BZip2 compression

FILTER_DEFLATE

Deflate compression

FILTER_ZSTD

ZStandard compression

FILTER_PPMD

PPMd compression

FILTER_BROTLI

Brotli compression

FILTER_COPY

No compression (store)

FILTER_DELTA

Delta filter

FILTER_X86, FILTER_ARM, FILTER_ARMTHUMB, FILTER_POWERPC, FILTER_SPARC, FILTER_IA64

BCJ branch converters for executable code

FILTER_CRYPTO_AES256_SHA256

7zAES encryption

PRESET_DEFAULT, PRESET_EXTREME

LZMA/LZMA2 preset values, from lzma

CHECK_NONE, CHECK_CRC32, CHECK_CRC64, CHECK_SHA256

Integrity check IDs, from lzma