all Python 3zlibfunction
zlib.compressobj()
compression
Creates a streaming compressor: feed data in chunks through compress(), and always finish with flush().
Syntax
c = zlib.compressobj(level=-1, method=DEFLATED, wbits=15, memLevel=8, strategy=Z_DEFAULT_STRATEGY, zdict=None)
Use it when data does not fit in memory or arrives in pieces. The main trap is forgetting flush(): compress() returns only what is ready, often an empty b'', and the tail plus checksum stay inside the object — without flush() the stream is truncated. The object cannot be used after flush(). With wbits=31 it writes the gzip format, and zdict gives a shared dictionary for short similar messages.
Examples
import zlib
c = zlib.compressobj()
parts = [c.compress(chunk) for chunk in (b'abc' * 100, b'xyz' * 100)]
print(len(b''.join(parts)) < 10) # → True — сжатое пока внутри объекта
try:
zlib.decompress(b''.join(parts))
except zlib.error:
print('без flush поток обрезан') # → без flush поток обрезан
parts.append(c.flush())
print(len(zlib.decompress(b''.join(parts)))) # → 600
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy