Gzip Compress Decompress Byte Roundtrip

gzip.compress and gzip.decompress roundtrip bytes through the gzip container format: repeated payloads shrink and restore byte-for-byte.

PythonData Integrity

Code

pythonsnippet
16 lines
import gzip

# gzip.compress / gzip.decompress 是 bytes 级别的往返(roundtrip)
payload = b"event: deploy\nservice: billing\n" * 20
packed = gzip.compress(payload)
print("raw bytes:", len(payload))
print("gzip bytes:", len(packed))

restored = gzip.decompress(packed)
print("restored equals original:", restored == payload)

# gzip 容器以 1f 8b 魔数开头,可当场校验
print("gzip magic header:", bytes([0x1F, 0x8B]) == packed[:2])

text = restored.decode("utf-8")
print("first line:", text.splitlines()[0])

Output

Captured from a sandboxed run of this snippet in the build pipeline.

raw bytes: 580
gzip bytes: 56
restored equals original: True
gzip magic header: True
first line: event: deployservice: billingevent: deployservice: billingevent: deployservice: billingevent: deployservice: billingevent: deployservice: billingevent: deployservice: billingevent: deployservice: billingevent: deployservice: billingevent: deployservice: billingevent: deployservice: billingevent: deployservice: billingevent: deployservice: billingevent: deployservice: billingevent: deployservice: billingevent: deployservice: billingevent: deployservice: billingevent: deployservice: billingevent: deployservice: billingevent: deployservice: billingevent: deployservice: billing

How the snippet works

Module-level bindings hold the data — payload, packed, restored, text — with no function scope in between.

What to watch for

  • Nothing to install: gzip ships with the Python standard library.

Using it

Running the file prints labeled results such as raw bytes:, gzip bytes:, restored equals original: — each operation’s effect is visible in the output.

Interactive Tools for This Topic

FAQ

Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `payload`, `packed`, `restored`.