bz2 — Support forbzip2 compression

Source code:Lib/bz2.py


This module provides a comprehensive interface for compressing anddecompressing data using the bzip2 compression algorithm.

Thebz2 module contains:

(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 afileobject.

As with the constructor forBZ2File, thefilename argument can bean actual filename (astr orbytes object), or an existingfile object to read from or write to.

Themode 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'.

Thecompresslevel argument is an integer from 1 to 9, as for theBZ2File constructor.

For binary mode, this function is equivalent to theBZ2Fileconstructor:BZ2File(filename,mode,compresslevel=compresslevel). Inthis case, theencoding,errors andnewline arguments must not beprovided.

For text mode, aBZ2File object is created, and wrapped in anio.TextIOWrapper instance with the specified encoding, errorhandling behavior, and line ending(s).

Added in version 3.3.

Άλλαξε στην έκδοση 3.4:The'x' (exclusive creation) mode was added.

Άλλαξε στην έκδοση 3.6:Accepts apath-like object.

classbz2.BZ2File(filename,mode='r',*,compresslevel=9)

Open a bzip2-compressed file in binary mode.

Iffilename is astr orbytes object, open the named filedirectly. Otherwise,filename should be afile object, which willbe used to read or write the compressed data.

Themode 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.

Iffilename 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'.

Ifmode 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.

Ifmode is'r', the input file may be the concatenation of multiplecompressed streams.

BZ2File provides all of the members specified by theio.BufferedIOBase, except fordetach()andtruncate().Iteration and thewith statement are supported.

BZ2File also provides the following methods and attributes:

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.

Σημείωση

While callingpeek() does not change the file position oftheBZ2File, it may change the position of the underlying fileobject (e.g. if theBZ2File was constructed by passing a fileobject forfilename).

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 tosize uncompressed bytes, while trying to avoidmaking multiple reads from the underlying stream. Reads up to abuffer’s worth of data if size is negative.

Returnsb'' if the file is at EOF.

Added in version 3.3.

readinto(b)

Read bytes intob.

Returns the number of bytes read (0 for EOF).

Added in version 3.3.

mode

'rb' for reading and'wb' for writing.

Added in version 3.13.

name

The bzip2 file name. Equivalent to thenameattribute of the underlyingfile object.

Added in version 3.13.

Άλλαξε στην έκδοση 3.1:Support for thewith statement was added.

Άλλαξε στην έκδοση 3.3:Support was added forfilename being afile object instead of anactual filename.

The'a' (append) mode was added, along with support for readingmulti-stream files.

Άλλαξε στην έκδοση 3.4:The'x' (exclusive creation) mode was added.

Άλλαξε στην έκδοση 3.5:Theread() method now accepts an argument ofNone.

Άλλαξε στην έκδοση 3.6:Accepts apath-like object.

Άλλαξε στην έκδοση 3.9:Thebuffering parameter has been removed. It was ignored and deprecatedsince Python 3.0. Pass an open file object to control how the file isopened.

Thecompresslevel parameter became keyword-only.

Άλλαξε στην έκδοση 3.10:This class is thread unsafe in the face of multiple simultaneousreaders or writers, just like its equivalent classes ingzip andlzma have always been.

Incremental (de)compression

classbz2.BZ2Compressor(compresslevel=9)

Create a new compressor object. This object may be used to compress dataincrementally. For one-shot compression, use thecompress() functioninstead.

compresslevel, if given, must be an integer between1 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.

classbz2.BZ2Decompressor

Create a new decompressor object. This object may be used to decompress dataincrementally. For one-shot compression, use thedecompress() functioninstead.

Σημείωση

This class does not transparently handle inputs containing multiplecompressed streams, unlikedecompress() andBZ2File. Ifyou need to decompress a multi-stream input withBZ2Decompressor,you must use a new decompressor for each stream.

decompress(data,max_length=-1)

Decompressdata (abytes-like object), returninguncompressed data as bytes. Some ofdata may be bufferedinternally, for use in later calls todecompress(). Thereturned data should be concatenated with the output of anyprevious calls todecompress().

Ifmax_length is nonnegative, returns at mostmax_lengthbytes of decompressed data. If this limit is reached and furtheroutput can be produced, theneeds_input attribute willbe set toFalse. In this case, the next call todecompress() may providedata asb'' to obtainmore of the output.

If all of the input data was decompressed and returned (eitherbecause this was less thanmax_length bytes, or becausemax_length was negative), theneeds_input attributewill be set toTrue.

Attempting to decompress data after the end of stream is reachedraises anEOFError. Any data found after the end of thestream is ignored and saved in theunused_data attribute.

Άλλαξε στην έκδοση 3.5:Added themax_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 beb''.

needs_input

False if thedecompress() method can provide moredecompressed data before requiring new uncompressed input.

Added in version 3.5.

One-shot (de)compression

bz2.compress(data,compresslevel=9)

Compressdata, abytes-like object.

compresslevel, if given, must be an integer between1 and9. Thedefault is9.

For incremental compression, use aBZ2Compressor instead.

bz2.decompress(data)

Decompressdata, abytes-like object.

Ifdata is the concatenation of multiple compressed streams, decompressall of the streams.

For incremental decompression, use aBZ2Decompressor instead.

Άλλαξε στην έκδοση 3.3:Support for multi-stream inputs was added.

Examples of usage

Below are some examples of typical usage of thebz2 module.

Usingcompress() anddecompress() to demonstrate round-trip compression:

>>>importbz2>>>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

UsingBZ2Compressor for incremental compression:

>>>importbz2>>>defgen_data(chunks=10,chunksize=1000):..."""Yield incremental blocks of chunksize bytes."""...for_inrange(chunks):...yieldb"z"*chunksize...>>>comp=bz2.BZ2Compressor()>>>out=b"">>>forchunkingen_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 ofb"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:

>>>importbz2>>>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.""">>>withbz2.open("myfile.bz2","wb")asf:...# Write compressed data to file...unused=f.write(data)...>>>withbz2.open("myfile.bz2","rb")asf:...# Decompress data from file...content=f.read()...>>>content==data# Check equality to original object after round-tripTrue