bz2 --- 对 bzip2 压缩算法的支持¶
源代码: Lib/bz2.py
此模块提供了使用 bzip2 压缩算法压缩和解压数据的一套完整的接口。
bz2 模块包含:
- 用于增量压缩和解压的 - BZ2Compressor和- BZ2Decompressor类。
- 用于一次性压缩和解压的 - compress()和- decompress()函数。
此模块中的所有类都能安全地从多个线程访问。
文件压缩和解压¶
- 
bz2.open(filename, mode='r', compresslevel=9, encoding=None, errors=None, newline=None)¶
- 以二进制或文本模式打开 bzip2 压缩文件,返回一个 file object。 - 和 - BZ2File的构造函数类似,filename 参数可以是一个实际的文件名(- str或- bytes对象),或是已有的可供读取或写入的文件对象。- mode 参数可设为二进制模式的 - 'r'、- 'rb'、- 'w'、- 'wb'、- 'x'、- 'xb'、- 'a'或- 'ab',或者文本模式的- 'rt'、- 'wt'、- 'xt'或- 'at'。默认是- 'rb'。- compresslevel 参数是 1 到 9 的整数,和 - BZ2File的构造函数一样。- 对于二进制模式,这个函数等价于 - BZ2File构造器:- BZ2File(filename, mode, compresslevel=compresslevel)。 在这种情况下,不可提供 encoding, errors 和 newline 参数。- 对于文本模式,将会创建一个 - BZ2File对象,并将它包装到一个- io.TextIOWrapper实例中,此实例带有指定的编码格式、错误处理行为和行结束符。- 3.3 新版功能. - 在 3.4 版更改: 添加了 - 'x'(单独创建) 模式。- 在 3.6 版更改: 接受一个 类路径对象。 
- 
class bz2.BZ2File(filename, mode='r', buffering=None, compresslevel=9)¶
- 用二进制模式打开 bzip2 压缩文件。 - 如果 filename 是一个 - str或- bytes对象,则打开名称对应的文件目录。 否则的话,filename 应当是一个 file object,它将被用来读取或写入压缩数据。- mode 参数可以是表示读取的 - 'r'(默认值),表示覆写的- 'w',表示单独创建的- 'x',或表示添加的- 'a'。 这些模式还可别以- 'rb',- 'wb',- 'xb'和- 'ab'的等价形式给出。- 如果 filename 是一个文件对象(而不是实际的文件名),则 - 'w'模式并不会截断文件,而是会等价于- 'a'。- buffering 参数会被忽略。 从 Python 3.0 开始它已被弃用。 - 如果 mode 为 - 'w'或- 'a',则 compresslevel 可以是- 1到- 9之间的整数,用于指定压缩等级:- 1产生最低压缩率,而- 9(默认值) 产生最高压缩率。- 如果 mode 为 - 'r',则输入文件可以为多个压缩流的拼接。- BZ2File提供了- io.BufferedIOBase所指定的所有成员,但- detach()和- truncate()除外。 并支持迭代和- with语句。- BZ2File还提供了以下方法:- 
peek([n])¶
- 返回缓冲的数据而不前移文件位置。 至少将返回一个字节的数据(除非为 EOF)。 实际返回的字节数不确定。 - 3.3 新版功能. 
 - 3.0 版后已移除: 关键字参数 buffering 已弃用,现在会被忽略。 - 在 3.1 版更改: 添加了对 - with语句的支持。- 在 3.3 版更改: 添加了 - fileno(),- readable(),- seekable(),- writable(),- read1()和- readinto()方法。- 在 3.3 版更改: 添加了对 filename 使用 file object 而非实际文件名的支持。 - 在 3.3 版更改: 添加了 - 'a'(append) 模式,以及对读取多数据流文件的支持。- 在 3.4 版更改: 添加了 - 'x'(单独创建) 模式。- 在 3.5 版更改: - read()方法现在接受- None作为参数。- 在 3.6 版更改: 接受一个 类路径对象。 
- 
增量压缩和解压¶
- 
class bz2.BZ2Compressor(compresslevel=9)¶
- 创建一个新的压缩器对象。 此对象可被用来执行增量数据压缩。 对于一次性压缩,请改用 - compress()函数。- 如果给定 compresslevel,它必须为 - 1至- 9之间的整数。 默认值为- 9。- 
flush()¶
- 结束压缩进程,返回内部缓冲中剩余的压缩完成的数据。 - 调用此方法之后压缩器对象将不可再被使用。 
 
- 
- 
class bz2.BZ2Decompressor¶
- 创建一个新的解压缩器对象。 此对象可被用来执行增量数据解压缩。 对于一次性解压缩,请改用 - decompress()函数。- 注解 - 这个类不会透明地处理包含多个已压缩数据流的输入,这不同于 - decompress()和- BZ2File。 如果你需要通过- BZ2Decompressor来解压缩多个数据流输入,你必须为每个数据流都使用新的解压缩器。- 
decompress(data, max_length=-1)¶
- Decompress data (a bytes-like object), returning uncompressed data as bytes. Some of data may be buffered internally, for use in later calls to - decompress(). The returned data should be concatenated with the output of any previous calls to- decompress().- If max_length is nonnegative, returns at most max_length bytes of decompressed data. If this limit is reached and further output can be produced, the - needs_inputattribute will be set to- False. In this case, the next call to- decompress()may provide data as- b''to obtain more of the output.- If all of the input data was decompressed and returned (either because this was less than max_length bytes, or because max_length was negative), the - needs_inputattribute will be set to- True.- Attempting to decompress data after the end of stream is reached raises an EOFError. Any data found after the end of the stream is ignored and saved in the - unused_dataattribute.- 在 3.5 版更改: Added the max_length parameter. 
 - 
eof¶
- 若达到了数据流末尾标识符则为 - True。- 3.3 新版功能. 
 - 
unused_data¶
- 压缩数据流的末尾还有数据。 - If this attribute is accessed before the end of the stream has been reached, its value will be - b''.
 - 
needs_input¶
- Falseif the- decompress()method can provide more decompressed data before requiring new uncompressed input.- 3.5 新版功能. 
 
- 
一次性压缩或解压¶
- 
bz2.compress(data, compresslevel=9)¶
- Compress data, a bytes-like object. - 如果给定 compresslevel,它必须为 - 1至- 9之间的整数。 默认值为- 9。- For incremental compression, use a - BZ2Compressorinstead.
- 
bz2.decompress(data)¶
- Decompress data, a bytes-like object. - If data is the concatenation of multiple compressed streams, decompress all of the streams. - For incremental decompression, use a - BZ2Decompressorinstead.- 在 3.3 版更改: 支持了多数据流的输入。 
用法示例¶
Below are some examples of typical usage of the bz2 module.
Using compress() and decompress() to demonstrate round-trip compression:
>>> import bz2
>>> data = b"""\
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
>>> c = bz2.compress(data)
>>> len(data) / len(c)  # Data compression ratio
1.513595166163142
>>> d = bz2.decompress(c)
>>> data == d  # Check equality to original object after round-trip
True
Using BZ2Compressor for incremental compression:
>>> import bz2
>>> def gen_data(chunks=10, chunksize=1000):
...     """Yield incremental blocks of chunksize bytes."""
...     for _ in range(chunks):
...         yield b"z" * chunksize
...
>>> comp = bz2.BZ2Compressor()
>>> out = b""
>>> for chunk in gen_data():
...     # Provide data to the compressor object
...     out = out + comp.compress(chunk)
...
>>> # Finish the compression process.  Call this once you have
>>> # finished providing data to the compressor.
>>> out = out + comp.flush()
The example above uses a very "nonrandom" stream of data (a stream of b"z" chunks). Random data tends to compress poorly, while ordered, repetitive data usually yields a high compression ratio.
Writing and reading a bzip2-compressed file in binary mode:
>>> import bz2
>>> data = b"""\
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
>>> with bz2.open("myfile.bz2", "wb") as f:
...     # Write compressed data to file
...     unused = f.write(data)
>>> with bz2.open("myfile.bz2", "rb") as f:
...     # Decompress data from file
...     content = f.read()
>>> content == data  # Check equality to original object after round-trip
True
