Source code: Lib/bz2.py
This module provides a comprehensive interface for compressing anddecompressing data using the bzip2 compression algorithm.
The bz2 module contains:
The open() function and BZ2File class for reading andwriting compressed files.
The BZ2Compressor and BZ2Decompressor classes forincremental (de)compression.
The compress() and decompress() functions for one-shot(de)compression.
(De)compression of files¶
- bz2.open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)¶
Open a bzip2-compressed file in binary or text mode, returning a fileobject.
As with the constructor for BZ2File, the filename argument can bean actual filename (a str or bytes object), or an existingfile object to read from or write to.
The mode argument can be any of
'r'
,'rb'
,'w'
,'wb'
,'x'
,'xb'
,'a'
or'ab'
for binary mode, or'rt'
,'wt'
,'xt'
, or'at'
for text mode. The default is'rb'
.The compresslevel argument is an integer from 1 to 9, as for theBZ2File constructor.
For binary mode, this function is equivalent to the BZ2Fileconstructor:
BZ2File(filename, mode, compresslevel=compresslevel)
. Inthis case, the encoding, errors and newline arguments must not beprovided.For text mode, a BZ2File object is created, and wrapped in anio.TextIOWrapper instance with the specified encoding, errorhandling behavior, and line ending(s).
Added in version 3.3.
Changed in version 3.4: The
'x'
(exclusive creation) mode was added.Changed in version 3.6: Accepts a path-like object.
- class bz2.BZ2File(filename, mode='r', *, compresslevel=9)¶
Open a bzip2-compressed file in binary mode.
If filename is a str or bytes object, open the named filedirectly. Otherwise, filename should be a file object, which willbe used to read or write the compressed data.
The mode argument can be either
'r'
for reading (default),'w'
foroverwriting,'x'
for exclusive creation, or'a'
for appending. Thesecan equivalently be given as'rb'
,'wb'
,'xb'
and'ab'
respectively.If filename is a file object (rather than an actual file name), a mode of
'w'
does not truncate the file, and is instead equivalent to'a'
.If mode is
'w'
or'a'
, compresslevel can be an integer between1
and9
specifying the level of compression:1
produces theleast compression, and9
(default) produces the most compression.If mode is
'r'
, the input file may be the concatenation of multiplecompressed streams.BZ2File provides all of the members specified by theio.BufferedIOBase, except for detach()and truncate().Iteration and the with statement are supported.
BZ2File also provides the following methods:
- peek([n])¶
Return buffered data without advancing the file position. At least onebyte of data will be returned (unless at EOF). The exact number of bytesreturned is unspecified.
Note
While calling peek() does not change the file position ofthe BZ2File, it may change the position of the underlying fileobject (e.g. if the BZ2File was constructed by passing a fileobject for filename).
Added in version 3.3.
- fileno()¶
Return the file descriptor for the underlying file.
Added in version 3.3.
- readable()¶
Return whether the file was opened for reading.
Added in version 3.3.
- seekable()¶
Return whether the file supports seeking.
Added in version 3.3.
- writable()¶
Return whether the file was opened for writing.
Added in version 3.3.
- read1(size=-1)¶
Read up to size uncompressed bytes, while trying to avoidmaking multiple reads from the underlying stream. Reads up to abuffer’s worth of data if size is negative.
Returns
b''
if the file is at EOF.Added in version 3.3.
- readinto(b)¶
Read bytes into b.
Returns the number of bytes read (0 for EOF).
Added in version 3.3.
Changed in version 3.1: Support for the with statement was added.
Changed in version 3.3: Support was added for filename being a file object instead of anactual filename.
The
'a'
(append) mode was added, along with support for readingmulti-stream files.Changed in version 3.4: The
'x'
(exclusive creation) mode was added.Changed in version 3.5: The read() method now accepts an argument of
None
.Changed in version 3.6: Accepts a path-like object.
Changed in version 3.9: The buffering parameter has been removed. It was ignored and deprecatedsince Python 3.0. Pass an open file object to control how the file isopened.
The compresslevel parameter became keyword-only.
Changed in version 3.10: This class is thread unsafe in the face of multiple simultaneousreaders or writers, just like its equivalent classes in gzip andlzma have always been.
Incremental (de)compression¶
- class bz2.BZ2Compressor(compresslevel=9)¶
Create a new compressor object. This object may be used to compress dataincrementally. For one-shot compression, use the compress() functioninstead.
compresslevel, if given, must be an integer between
1
and9
. Thedefault is9
.- compress(data)¶
Provide data to the compressor object. Returns a chunk of compressed dataif possible, or an empty byte string otherwise.
When you have finished providing data to the compressor, call theflush() method to finish the compression process.
- flush()¶
Finish the compression process. Returns the compressed data left ininternal buffers.
The compressor object may not be used after this method has been called.
- class bz2.BZ2Decompressor¶
Create a new decompressor object. This object may be used to decompress dataincrementally. For one-shot compression, use the decompress() functioninstead.
Note
This class does not transparently handle inputs containing multiplecompressed streams, unlike decompress() and BZ2File. Ifyou need to decompress a multi-stream input with BZ2Decompressor,you must use a new decompressor for each stream.
- decompress(data, max_length=-1)¶
Decompress data (a bytes-like object), returninguncompressed data as bytes. Some of data may be bufferedinternally, for use in later calls to decompress(). Thereturned data should be concatenated with the output of anyprevious calls to decompress().
If max_length is nonnegative, returns at most max_lengthbytes of decompressed data. If this limit is reached and furtheroutput can be produced, the needs_input attribute willbe set to
False
. In this case, the next call todecompress() may provide data asb''
to obtainmore of the output.If all of the input data was decompressed and returned (eitherbecause this was less than max_length bytes, or becausemax_length was negative), the needs_input attributewill be set to
True
.Attempting to decompress data after the end of stream is reachedraises an EOFError. Any data found after the end of thestream is ignored and saved in the unused_data attribute.
Changed in version 3.5: Added the max_length parameter.
- eof¶
True
if the end-of-stream marker has been reached.Added in version 3.3.
- unused_data¶
Data found after the end of the compressed stream.
If this attribute is accessed before the end of the stream has beenreached, its value will be
b''
.
- needs_input¶
False
if the decompress() method can provide moredecompressed data before requiring new uncompressed input.Added in version 3.5.
One-shot (de)compression¶
- bz2.compress(data, compresslevel=9)¶
Compress data, a bytes-like object.
compresslevel, if given, must be an integer between
1
and9
. Thedefault is9
.For incremental compression, use a BZ2Compressor instead.
- bz2.decompress(data)¶
Decompress data, a bytes-like object.
If data is the concatenation of multiple compressed streams, decompressall of the streams.
For incremental decompression, use a BZ2Decompressor instead.
Changed in version 3.3: Support for multi-stream inputs was added.
Examples of usage¶
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 ratio1.513595166163142>>> d = bz2.decompress(c)>>> data == d # Check equality to original object after round-tripTrue
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-tripTrue