Python Glossary Русский

all Python 3bz2term

bz2.BZ2Compressor

streaming compression

An object for streaming bzip2 compression piece by piece: data is fed in parts and the compressed result is assembled from compress() and flush().

Syntax

c = bz2.BZ2Compressor(compresslevel=9)

compress() often returns empty bytes — bzip2 buffers a block of up to 900 KB — and that is not an error: flush() hands over everything buffered. A forgotten flush() yields a truncated archive. After flush() the object is spent: the next compress() raises ValueError, and a new stream needs a new compressor.

Examples

import bz2
c = bz2.BZ2Compressor()
parts = [c.compress(b'abc' * 1000) for _ in range(3)]
print(parts)  # → [b'', b'', b''] — всё ещё в буфере
data = b''.join(parts) + c.flush()
print(bz2.decompress(data) == b'abc' * 3000)  # → True
try:
    c.compress(b'more')
except ValueError as e:
    print(e)  # → Compressor has been flushed

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy