Compress Data and Streams with gzip
Core idea
gzip compresses bytes into a gzip-format stream. compress(data) and decompress(data) work on complete byte values; GzipFile wraps a binary stream and exposes read and write operations. Close the writer before reading its completed output. For text, encode or use a text-mode wrapper.
import gzipraw = b"sensor:42\n" * 20packed = gzip.compress(raw, mtime=0)print(gzip.decompress(packed) == raw)The restored bytes match exactly. mtime=0 removes the timestamp from this example, but does not promise identical compressed bytes across environments.
Read a compressed stream
import gzipfrom io import BytesIObuffer = BytesIO()with gzip.GzipFile(fileobj=buffer, mode="wb") as writer: writer.write(b"A\nB\n")buffer.seek(0)with gzip.GzipFile(fileobj=buffer, mode="rb") as reader: print(reader.readline())The stream returns decompressed bytes. The external BytesIO remains open after the writer closes.
Common mistake
Compression is not encryption. One-shot decompression may allocate a large result; reserve it for bounded trusted inputs.
Practice
Compress a short UTF-8 message, decompress it and decode it; compare the resulting text.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Gzip streams
Check your understanding of gzip streams.
What is printed?
import gzipprint(gzip.decompress(gzip.compress(b"abc")))What is printed?
import gzipfrom io import BytesIOb=BytesIO()with gzip.GzipFile(fileobj=b,mode="wb") as f: f.write(b"x")print(b.closed)Which operation completes a gzip writer?
What does gzip alone not provide?