On this page
  1. gzip
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Streaming Compressed Text Files (gzip.open)
  7. 2. Deterministic Reproducible .gz Output (mtime=0)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

gzip

Prev: grp | Up: stdlib_module | Next: hashlib
Rel: pickle, copyreg, shelve, marshal, dbm
Ref: docs.python.org — gzip
Tags: #public #python3 #stdlib


Import

import gzip

Overview

Reads and writes .gz compressed files and in-memory byte streams (wrapping zlib with standard gzip headers and CRC32 integrity checks). Reach for gzip.open(..., "rt", encoding="utf-8") to stream large compressed logs or JSONL datasets line by line without decompressing the entire file to disk.

Quick Start

import gzip

raw = b"repeated text " * 100
compressed = gzip.compress(raw, compresslevel=6)
assert len(compressed) < len(raw)
assert gzip.decompress(compressed) == raw

Implementation Walkthrough

1. Streaming Compressed Text Files (gzip.open)

import gzip
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    gz_path = Path(tmp) / "events.jsonl.gz"
    with gzip.open(gz_path, "wt", encoding="utf-8") as fh:
        fh.write('{"id": 1}\n{"id": 2}\n')

    with gzip.open(gz_path, "rt", encoding="utf-8") as fh:
        lines = [line.strip() for line in fh]
    assert lines == ['{"id": 1}', '{"id": 2}']

2. Deterministic Reproducible .gz Output (mtime=0)

By default, gzip embeds the current wall-clock timestamp in the header; pass mtime=0 for reproducible builds and deterministic hashes:

import gzip

a = gzip.compress(b"payload", mtime=0)
b = gzip.compress(b"payload", mtime=0)
assert a == b

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes