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!
The module defines the following items:
- class py7zr.SevenZipFile[source]
The class for reading 7z files. See section sevenzipfile-object
- class py7zr.FileInfo[source]¶
The class used to represent information about a member of an archive file. See section
- py7zr.is_7zfile(filename)[source]¶
Returns
True
if filename is a valid 7z file based on its magic number, otherwise returnsFalse
. filename may be a file or file-like object too.
- py7zr.unpack_7zarchive(archive, path, extra=None)[source]¶
Helper function to intend to use with
shutil
module which offers a number of high-level operations on files and collections of files. Sinceshutil
has a function to register decompressor of archive, you can register an helper function and then you can extract archive by callingshutil.unpack_archive()
shutil.register_unpack_format('7zip', ['.7z'], unpack_7zarchive)
shutil.unpack_archive(filename, extract_dir)
- py7zr.pack_7zarchive(archive, path, extra=None)[source]¶
Helper function to intend to use with
shutil
module which offers a number of high-level operations on files and collections of files. Sinceshutil
has a function to register maker of archive, you can register an helper function and then you can produce archive by callingshutil.make_archive()
shutil.register_archive_format('7zip', pack_7zarchive, description='7zip archive')
shutil.make_archive(base_name, '7zip', base_dir)
See also
(external link) shutil shutil
module offers a number of high-level operations on files and collections of files.
Class description¶
ArchiveInfo Object¶
- class py7zr.ArchiveInfo(filename, stat, header_size, method_names, solid, blocks, uncompressed)[source]¶
Data only python object to hold information of archive. The object can be retrieved by archiveinfo() method of SevenZipFile object.
- py7zr.filename: str¶
filename of 7zip archive. If SevenZipFile object is created from BinaryIO object, it becomes None.
- py7zr.stat: stat_result¶
fstat object of 7zip archive. If SevenZipFile object is created from BinaryIO object, it becomes None.
- py7zr.header_size: int¶
header size of 7zip archive.
- py7zr.method_names: List[str]¶
list of method names used in 7zip archive. If method is not supported by py7zr, name has a postfix asterisk(*) mark.
- py7zr.solid: bool¶
Whether is 7zip archive a solid compression or not.
- py7zr.blocks: int¶
number of compression block(s)
- py7zr.uncompressed: int¶
total uncompressed size of files in 7zip archive
SevenZipFile Object¶
- class py7zr.SevenZipFile(file, mode='r', filters=None, dereference=False, password=None)[source]¶
Open a 7z file, where file can be a path to a file (a string), a file-like object or a path-like object.
The mode parameter should be
'r'
to read an existing file,'w'
to truncate and write a new file,'a'
to append to an existing file, or'x'
to exclusively create and write a new file. If mode is'x'
and file refers to an existing file, aFileExistsError
will be raised. If mode is'r'
or'a'
, the file should be seekable.The filters parameter controls the compression algorithms to use when writing files to the archive.
SevenZipFile class has a capability as context manager. It can handle ‘with’ statement.
If dereference is False, add symbolic and hard links to the archive. If it is True, add the content of the target files to the archive. This has no effect on systems that do not support symbolic links.
When password given, py7zr handles an archive as an encrypted one.
- SevenZipFile.close()[source]¶
Close the archive file and release internal buffers. You must call
close()
before exiting your program or most records will not be written.
- SevenZipFile.getnames()[source]¶
- SevenZipFile.namelist()[source]¶
Return a list of archive files by name.
- SevenZipFile.getinfo(name)[source]¶
Return a FileInfo object with information about the archive member name. Calling
getinfo()
for a name not currently contained in the archive will raise aKeyError
.
- SevenZipFile.needs_password()[source]¶
Return True if the archive is encrypted, or is going to create encrypted archive. Otherwise return False
- SevenZipFile.extractall(path=None, recursive=True, *, progress_callback, factory)[source]¶
Extract all members from the archive to current working directory.
- SevenZipFile.extract(path=None, targets=None, recursive=True, *, progress_callback, factory)[source]¶
Extract specified pathspec archived files to current working directory. ‘path’ specifies a different directory to extract to.
‘targets’ is a COLLECTION of archived file names to be extracted. py7zr looks for files and directories as same as specified in element of ‘targets’.
When the method gets a
str
object or another object other than collection such as LIST or SET, it will raiseTypeError
.Once extract() called, the
SevenZipFile
object become exhausted, and an EOF state. If you want to callextract()
,extractall()
again, you should callreset()
before it.CAUTION when specifying files and not specifying parent directory, py7zr will fails with no such directory. When you want to extract file ‘somedir/somefile’ then pass a list: [‘somedirectory’, ‘somedir/somefile’] as a target argument.
‘recursive’ is a BOOLEAN which if set True, helps with simplifying subcontents extraction.
Instead of specifying all files / directories under a parent directory by passing a list of ‘targets’, specifying only the parent directory and setting ‘recursive’ to True forces an automatic extraction of all subdirectories and sub-contents recursively.
If ‘recursive’ is not set, it defaults to False, so the extraction proceeds as if the parameter did not exist.
Please see ‘tests/test_basic.py: test_py7zr_extract_and_getnames()’ for example code.
‘progress_callback’ is an object to give a extraction progress to caller.
‘factory’ is an object to extract user specified object other than file system. When ‘factory’ specified, path is ignored. ‘factory’ object should implement Py7zIO interface.
filter_pattern = re.compile(r'scripts.*')
with SevenZipFile('archive.7z', 'r') as zip:
allfiles = zip.getnames()
targets = [f if filter_pattern.match(f) for f in allfiles]
with SevenZipFile('archive.7z', 'r') as zip:
zip.extract(targets=targets)
with SevenZipFile('archive.7z', 'r') as zip:
zip.extract(targets=targets, recursive=True)
class MyIO(Py7zIO):
def __init__(self, limit):
self.limit = limit
self.buf = None
self.empty = True
def write(self, s: [bytes, bytearray]):
"""keep only bytes of limit"""
if self.empty:
self.buf = s[:self.limit]
self.empty = False
def read(self, length: int = 0) -> bytes:
if self.empty:
return None
return self.buf[:length]
def seek(self, offset: int, whence: int = 0) -> int:
return 0
def size(self) -> int:
return len(self.buf)
class MyFactory(WriterFactory):
def __init(self, size):
self.size = size
self.products = {}
def create(self, fname) -> Py7zIO:
product = MyIO(self.size)
self.products[fname] = product
return product
size = 10
factory = MyFactory(size)
with SevenZipFile('archive.7z', 'r') as zip:
zip.extractall(factory=factory)
for fname in factory.products.keys():
print(f'{fname}: {factory.products[fname].read(size)}...')
- SevenZipFile.test()[source]¶
Read all the archive file and check a packed CRC. Return
True
if CRC check passed, and returnFalse
when detect defeat, or returnNone
when the archive don’t have a CRC record.
- SevenZipFile.testzip()[source]¶
Read all the files in the archive and check their CRCs. Return the name of the first bad file, or else return
None
. When the archive don’t have a CRC record, it returnNone
.
- SevenZipFile.write(filename, arcname=None)[source]¶
Write the file named filename to the archive, giving it the archive name arcname (by default, this will be the same as filename, but without a drive letter and with leading path separators removed). The archive must be open with mode
'w'
- SevenZipFile.writeall(filename, arcname=None)[source]¶
Write the directory and its sub items recursively into the archive, giving the archive name arcname (by default, this will be the same as filename, but without a drive letter and with leading path seaprator removed).
If you want to store directories and files, putting arcname is good idea. When filename is ‘C:/a/b/c’ and arcname is ‘c’, with a file exist as ‘C:/a/b/c/d.txt’, then archive listed as [‘c’, ‘c/d.txt’], the former as directory.
- SevenZipFile.set_encrypted_header(mode)[source]¶
Set header encryption mode. When encrypt header, set mode to True, otherwise False. Default is False.
- SevenZipFile.set_encoded_header_mode(mode)[source]¶
Set header encode mode. When encode header data, set mode to True, otherwise False. Default is True.
- SevenZipFile.filename¶
Name of the SEVEN ZIP file.
Compression Methods¶
‘py7zr’ supports algorithms and filters which lzma module and liblzma support. It also support BZip2 and Deflate that are implemented in python core libraries, and ZStandard with third party libraries. py7zr, python3 core lzma module and liblzma do not support some algorithms such as PPMd, BCJ2 and Deflate64.
Here is a table of algorithms.
# |
Category |
Algorithm |
Note |
---|---|---|---|
1 |
|
LZMA2 |
default (LZMA2+BCJ) |
2 |
LZMA |
||
3 |
Bzip2 |
||
4 |
Deflate |
||
5 |
COPY |
||
6 |
PPMd |
depend on pyppmd |
|
7 |
ZStandard |
depend on pyzstd |
|
8 |
Brotli |
depend on brotli,brotliCFFI |
|
9 |
|
BCJ |
|
10 |
Delta |
||
11 |
|
7zAES |
depend on pycryptodomex |
12 |
|
BCJ2 |
|
13 |
Deflate64 |
A feature handling symbolic link is basically compatible with ‘p7zip’ implementation, but not work with original 7-zip because the original does not implement the feature.
Possible filters value¶
Here is a list of examples for possible filters values. You can use it when creating SevenZipFile object.
from py7zr import FILTER_LZMA, SevenZipFile
filters = [{'id': FILTER_LZMA}]
archive = SevenZipFile('target.7z', mode='w', filters=filters)
- LZMA2 + Delta
[{'id': FILTER_DELTA}, {'id': FILTER_LZMA2, 'preset': PRESET_DEFAULT}]
- LZMA2 + BCJ
[{'id': FILTER_X86}, {'id': FILTER_LZMA2, 'preset': PRESET_DEFAULT}]
- LZMA2 + ARM
[{'id': FILTER_ARM}, {'id': FILTER_LZMA2, 'preset': PRESET_DEFAULT}]
- LZMA + BCJ
[{'id': FILTER_X86}, {'id': FILTER_LZMA}]
- LZMA2
[{'id': FILTER_LZMA2, 'preset': PRESET_DEFAULT}]
- LZMA
[{'id': FILTER_LZMA}]
- BZip2
[{'id': FILTER_BZIP2}]
- Deflate
[{'id': FILTER_DEFLATE}]
- ZStandard
[{'id': FILTER_ZSTD, 'level': 3}]
- PPMd
[{'id': FILTER_PPMD, 'order': 6, 'mem': 24}]
[{'id': FILTER_PPMD, 'order': 6, 'mem': "16m"}]
- Brolti
[{'id': FILTER_BROTLI, 'level': 11}]
- 7zAES + LZMA2 + Delta
[{'id': FILTER_DELTA}, {'id': FILTER_LZMA2, 'preset': PRESET_DEFAULT}, {'id': FILTER_CRYPTO_AES256_SHA256}]
- 7zAES + LZMA2 + BCJ
[{'id': FILTER_X86}, {'id': FILTER_LZMA2, 'preset': PRESET_DEFAULT}, {'id': FILTER_CRYPTO_AES256_SHA256}]
- 7zAES + LZMA
[{'id': FILTER_LZMA}, {'id': FILTER_CRYPTO_AES256_SHA256}]
- 7zAES + Deflate
[{'id': FILTER_DEFLATE}, {'id': FILTER_CRYPTO_AES256_SHA256}]
- 7zAES + BZip2
[{'id': FILTER_BZIP2}, {'id': FILTER_CRYPTO_AES256_SHA256}]
- 7zAES + ZStandard
[{'id': FILTER_ZSTD}, {'id': FILTER_CRYPTO_AES256_SHA256}]
Footnotes