all Python 3bz2function
bz2.compress()
in-memory compression
Compresses bytes with bzip2 in a single call and returns the compressed bytes. For data that fits in memory as a whole.
Syntax
data = bz2.compress(data, compresslevel=9)
It accepts bytes-like objects only: encode a string first, or you get TypeError. On small data the result can be longer than the input — the format has a header. bzip2 squeezes text tighter than zlib but is noticeably slower; the output depends on the library version, so tests should check a round trip rather than compare compressed bytes.
Examples
import bz2
text = 'повтор ' * 1000
packed = bz2.compress(text.encode('utf-8'))
print(len(packed) < len(text)) # → True
print(bz2.decompress(packed).decode('utf-8') == text) # → True
try:
bz2.compress('строка')
except TypeError:
print('нужны bytes') # → нужны bytes
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy