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.
Code
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: billingHow 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:
gzipships 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
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.