• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`bz2` --- Support for :program:`bzip2` compression
2=======================================================
3
4.. module:: bz2
5   :synopsis: Interfaces for bzip2 compression and decompression.
6
7.. moduleauthor:: Gustavo Niemeyer <niemeyer@conectiva.com>
8.. moduleauthor:: Nadeem Vawda <nadeem.vawda@gmail.com>
9.. sectionauthor:: Gustavo Niemeyer <niemeyer@conectiva.com>
10.. sectionauthor:: Nadeem Vawda <nadeem.vawda@gmail.com>
11
12**Source code:** :source:`Lib/bz2.py`
13
14--------------
15
16This module provides a comprehensive interface for compressing and
17decompressing data using the bzip2 compression algorithm.
18
19The :mod:`bz2` module contains:
20
21* The :func:`.open` function and :class:`BZ2File` class for reading and
22  writing compressed files.
23* The :class:`BZ2Compressor` and :class:`BZ2Decompressor` classes for
24  incremental (de)compression.
25* The :func:`compress` and :func:`decompress` functions for one-shot
26  (de)compression.
27
28
29(De)compression of files
30------------------------
31
32.. function:: open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)
33
34   Open a bzip2-compressed file in binary or text mode, returning a :term:`file
35   object`.
36
37   As with the constructor for :class:`BZ2File`, the *filename* argument can be
38   an actual filename (a :class:`str` or :class:`bytes` object), or an existing
39   file object to read from or write to.
40
41   The *mode* argument can be any of ``'r'``, ``'rb'``, ``'w'``, ``'wb'``,
42   ``'x'``, ``'xb'``, ``'a'`` or ``'ab'`` for binary mode, or ``'rt'``,
43   ``'wt'``, ``'xt'``, or ``'at'`` for text mode. The default is ``'rb'``.
44
45   The *compresslevel* argument is an integer from 1 to 9, as for the
46   :class:`BZ2File` constructor.
47
48   For binary mode, this function is equivalent to the :class:`BZ2File`
49   constructor: ``BZ2File(filename, mode, compresslevel=compresslevel)``. In
50   this case, the *encoding*, *errors* and *newline* arguments must not be
51   provided.
52
53   For text mode, a :class:`BZ2File` object is created, and wrapped in an
54   :class:`io.TextIOWrapper` instance with the specified encoding, error
55   handling behavior, and line ending(s).
56
57   .. versionadded:: 3.3
58
59   .. versionchanged:: 3.4
60      The ``'x'`` (exclusive creation) mode was added.
61
62   .. versionchanged:: 3.6
63      Accepts a :term:`path-like object`.
64
65
66.. class:: BZ2File(filename, mode='r', *, compresslevel=9)
67
68   Open a bzip2-compressed file in binary mode.
69
70   If *filename* is a :class:`str` or :class:`bytes` object, open the named file
71   directly. Otherwise, *filename* should be a :term:`file object`, which will
72   be used to read or write the compressed data.
73
74   The *mode* argument can be either ``'r'`` for reading (default), ``'w'`` for
75   overwriting, ``'x'`` for exclusive creation, or ``'a'`` for appending. These
76   can equivalently be given as ``'rb'``, ``'wb'``, ``'xb'`` and ``'ab'``
77   respectively.
78
79   If *filename* is a file object (rather than an actual file name), a mode of
80   ``'w'`` does not truncate the file, and is instead equivalent to ``'a'``.
81
82   If *mode* is ``'w'`` or ``'a'``, *compresslevel* can be an integer between
83   ``1`` and ``9`` specifying the level of compression: ``1`` produces the
84   least compression, and ``9`` (default) produces the most compression.
85
86   If *mode* is ``'r'``, the input file may be the concatenation of multiple
87   compressed streams.
88
89   :class:`BZ2File` provides all of the members specified by the
90   :class:`io.BufferedIOBase`, except for :meth:`detach` and :meth:`truncate`.
91   Iteration and the :keyword:`with` statement are supported.
92
93   :class:`BZ2File` also provides the following method:
94
95   .. method:: peek([n])
96
97      Return buffered data without advancing the file position. At least one
98      byte of data will be returned (unless at EOF). The exact number of bytes
99      returned is unspecified.
100
101      .. note:: While calling :meth:`peek` does not change the file position of
102         the :class:`BZ2File`, it may change the position of the underlying file
103         object (e.g. if the :class:`BZ2File` was constructed by passing a file
104         object for *filename*).
105
106      .. versionadded:: 3.3
107
108
109   .. versionchanged:: 3.1
110      Support for the :keyword:`with` statement was added.
111
112   .. versionchanged:: 3.3
113      The :meth:`fileno`, :meth:`readable`, :meth:`seekable`, :meth:`writable`,
114      :meth:`read1` and :meth:`readinto` methods were added.
115
116   .. versionchanged:: 3.3
117      Support was added for *filename* being a :term:`file object` instead of an
118      actual filename.
119
120   .. versionchanged:: 3.3
121      The ``'a'`` (append) mode was added, along with support for reading
122      multi-stream files.
123
124   .. versionchanged:: 3.4
125      The ``'x'`` (exclusive creation) mode was added.
126
127   .. versionchanged:: 3.5
128      The :meth:`~io.BufferedIOBase.read` method now accepts an argument of
129      ``None``.
130
131   .. versionchanged:: 3.6
132      Accepts a :term:`path-like object`.
133
134   .. versionchanged:: 3.9
135      The *buffering* parameter has been removed. It was ignored and deprecated
136      since Python 3.0. Pass an open file object to control how the file is
137      opened.
138
139      The *compresslevel* parameter became keyword-only.
140
141   .. versionchanged:: 3.10
142      This class is thread unsafe in the face of multiple simultaneous
143      readers or writers, just like its equivalent classes in :mod:`gzip` and
144      :mod:`lzma` have always been.
145
146
147Incremental (de)compression
148---------------------------
149
150.. class:: BZ2Compressor(compresslevel=9)
151
152   Create a new compressor object. This object may be used to compress data
153   incrementally. For one-shot compression, use the :func:`compress` function
154   instead.
155
156   *compresslevel*, if given, must be an integer between ``1`` and ``9``. The
157   default is ``9``.
158
159   .. method:: compress(data)
160
161      Provide data to the compressor object. Returns a chunk of compressed data
162      if possible, or an empty byte string otherwise.
163
164      When you have finished providing data to the compressor, call the
165      :meth:`flush` method to finish the compression process.
166
167
168   .. method:: flush()
169
170      Finish the compression process. Returns the compressed data left in
171      internal buffers.
172
173      The compressor object may not be used after this method has been called.
174
175
176.. class:: BZ2Decompressor()
177
178   Create a new decompressor object. This object may be used to decompress data
179   incrementally. For one-shot compression, use the :func:`decompress` function
180   instead.
181
182   .. note::
183      This class does not transparently handle inputs containing multiple
184      compressed streams, unlike :func:`decompress` and :class:`BZ2File`. If
185      you need to decompress a multi-stream input with :class:`BZ2Decompressor`,
186      you must use a new decompressor for each stream.
187
188   .. method:: decompress(data, max_length=-1)
189
190      Decompress *data* (a :term:`bytes-like object`), returning
191      uncompressed data as bytes. Some of *data* may be buffered
192      internally, for use in later calls to :meth:`decompress`. The
193      returned data should be concatenated with the output of any
194      previous calls to :meth:`decompress`.
195
196      If *max_length* is nonnegative, returns at most *max_length*
197      bytes of decompressed data. If this limit is reached and further
198      output can be produced, the :attr:`~.needs_input` attribute will
199      be set to ``False``. In this case, the next call to
200      :meth:`~.decompress` may provide *data* as ``b''`` to obtain
201      more of the output.
202
203      If all of the input data was decompressed and returned (either
204      because this was less than *max_length* bytes, or because
205      *max_length* was negative), the :attr:`~.needs_input` attribute
206      will be set to ``True``.
207
208      Attempting to decompress data after the end of stream is reached
209      raises an `EOFError`.  Any data found after the end of the
210      stream is ignored and saved in the :attr:`~.unused_data` attribute.
211
212      .. versionchanged:: 3.5
213         Added the *max_length* parameter.
214
215   .. attribute:: eof
216
217      ``True`` if the end-of-stream marker has been reached.
218
219      .. versionadded:: 3.3
220
221
222   .. attribute:: unused_data
223
224      Data found after the end of the compressed stream.
225
226      If this attribute is accessed before the end of the stream has been
227      reached, its value will be ``b''``.
228
229   .. attribute:: needs_input
230
231      ``False`` if the :meth:`.decompress` method can provide more
232      decompressed data before requiring new uncompressed input.
233
234      .. versionadded:: 3.5
235
236
237One-shot (de)compression
238------------------------
239
240.. function:: compress(data, compresslevel=9)
241
242   Compress *data*, a :term:`bytes-like object <bytes-like object>`.
243
244   *compresslevel*, if given, must be an integer between ``1`` and ``9``. The
245   default is ``9``.
246
247   For incremental compression, use a :class:`BZ2Compressor` instead.
248
249
250.. function:: decompress(data)
251
252   Decompress *data*, a :term:`bytes-like object <bytes-like object>`.
253
254   If *data* is the concatenation of multiple compressed streams, decompress
255   all of the streams.
256
257   For incremental decompression, use a :class:`BZ2Decompressor` instead.
258
259   .. versionchanged:: 3.3
260      Support for multi-stream inputs was added.
261
262.. _bz2-usage-examples:
263
264Examples of usage
265-----------------
266
267Below are some examples of typical usage of the :mod:`bz2` module.
268
269Using :func:`compress` and :func:`decompress` to demonstrate round-trip compression:
270
271    >>> import bz2
272    >>> data = b"""\
273    ... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
274    ... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
275    ... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
276    ... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
277    ... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
278    ... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
279    ... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
280    >>> c = bz2.compress(data)
281    >>> len(data) / len(c)  # Data compression ratio
282    1.513595166163142
283    >>> d = bz2.decompress(c)
284    >>> data == d  # Check equality to original object after round-trip
285    True
286
287Using :class:`BZ2Compressor` for incremental compression:
288
289    >>> import bz2
290    >>> def gen_data(chunks=10, chunksize=1000):
291    ...     """Yield incremental blocks of chunksize bytes."""
292    ...     for _ in range(chunks):
293    ...         yield b"z" * chunksize
294    ...
295    >>> comp = bz2.BZ2Compressor()
296    >>> out = b""
297    >>> for chunk in gen_data():
298    ...     # Provide data to the compressor object
299    ...     out = out + comp.compress(chunk)
300    ...
301    >>> # Finish the compression process.  Call this once you have
302    >>> # finished providing data to the compressor.
303    >>> out = out + comp.flush()
304
305The example above uses a very "nonrandom" stream of data
306(a stream of `b"z"` chunks).  Random data tends to compress poorly,
307while ordered, repetitive data usually yields a high compression ratio.
308
309Writing and reading a bzip2-compressed file in binary mode:
310
311    >>> import bz2
312    >>> data = b"""\
313    ... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
314    ... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
315    ... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
316    ... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
317    ... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
318    ... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
319    ... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
320    >>> with bz2.open("myfile.bz2", "wb") as f:
321    ...     # Write compressed data to file
322    ...     unused = f.write(data)
323    >>> with bz2.open("myfile.bz2", "rb") as f:
324    ...     # Decompress data from file
325    ...     content = f.read()
326    >>> content == data  # Check equality to original object after round-trip
327    True
328
329.. testcleanup::
330
331   import os
332   os.remove("myfile.bz2")
333