bz2
---bzip2 壓縮的支援¶
原始碼:Lib/bz2.py
This module provides a comprehensive interface for compressing anddecompressing data using the bzip2 compression algorithm.
Thebz2
module contains:
The
open()
function andBZ2File
class for reading andwriting compressed files.The
BZ2Compressor
andBZ2Decompressor
classes forincremental (de)compression.The
compress()
anddecompress()
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 afileobject.
As with the constructor for
BZ2File
, 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 the
BZ2File
constructor.For binary mode, this function is equivalent to the
BZ2File
constructor:BZ2File(filename,mode,compresslevel=compresslevel)
. Inthis case, theencoding,errors andnewline 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).在 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 a
str
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 calling
peek()
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).在 3.3 版被加入.
- fileno()¶
Return the file descriptor for the underlying file.
在 3.3 版被加入.
- readable()¶
Return whether the file was opened for reading.
在 3.3 版被加入.
- seekable()¶
Return whether the file supports seeking.
在 3.3 版被加入.
- writable()¶
Return whether the file was opened for writing.
在 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.
Returns
b''
if the file is at EOF.在 3.3 版被加入.
- readinto(b)¶
Read bytes intob.
Returns the number of bytes read (0 for EOF).
在 3.3 版被加入.
- mode¶
'rb'
for reading and'wb'
for writing.在 3.13 版被加入.
- name¶
The bzip2 file name. Equivalent to the
name
attribute of the underlyingfile object.在 3.13 版被加入.
在 3.1 版的變更:Support for the
with
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 版的變更:The
read()
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.
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 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 the
flush()
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 the
decompress()
functioninstead.備註
This class does not transparently handle inputs containing multiplecompressed streams, unlike
decompress()
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 to
decompress()
. 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, the
needs_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), the
needs_input
attributewill be set toTrue
.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 theunused_data
attribute.在 3.5 版的變更:新增max_length 參數。
- eof¶
True
if the end-of-stream marker has been reached.在 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 thedecompress()
method can provide moredecompressed data before requiring new uncompressed input.在 3.5 版被加入.
One-shot (de)compression¶
- bz2.compress(data,compresslevel=9)¶
Compressdata, abytes-like object.
compresslevel, if given, must be an integer between
1
and9
. Thedefault is9
.For incremental compression, use a
BZ2Compressor
instead.
- bz2.decompress(data)¶
Decompressdata, abytes-like object.
Ifdata is the concatenation of multiple compressed streams, decompressall of the streams.
For incremental decompression, use a
BZ2Decompressor
instead.在 3.3 版的變更:Support for multi-stream inputs was added.
用法範例¶
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