How to Compress Pipeline Output Gzip Per Partition in Python

Compress each partition of pipeline output into a separate gzip file and verify the compressed data by reading it back.

Easy Python 3.9+ Aug 9, 2026 Data pipelines & processing 13 views 0 copies

Python code

37 lines
Python 3.9+
import gzip
import io
import random
from pathlib import Path


def compress_partition(partition_data: list[str], output_path: Path) -> int:
    """Compress a partition of data to a gzip file, returns bytes written."""
    with gzip.open(output_path, 'wt', encoding='utf-8') as f:
        f.writelines(partition_data)
    return output_path.stat().st_size


def generate_partition(size: int = 10_000) -> list[str]:
    """Generate sample partition data (lines with random numbers)."""
    return [f"Record {i}: value={random.randint(1, 1000)}\n"
            for i in range(size)]


if __name__ == "__main__":
    # Create a temp directory for output
    out_dir = Path("./compressed_partitions")
    out_dir.mkdir(exist_ok=True)

    # Simulate processing 3 partitions of a pipeline
    for partition_num in range(3):
        data = generate_partition(size=10_000)
        output_file = out_dir / f"partition_{partition_num}.csv.gz"
        compressed_size = compress_partition(data, output_file)

        # Verify decompression works
        with gzip.open(output_file, 'rt', encoding='utf-8') as f:
            first_line = f.readline().strip()
            lines_count = sum(1 for _ in f) + 1

        print(f"Partition {partition_num}: {compressed_size} bytes, "
              f"{lines_count} lines, first line: '{first_line}'")

Output

stdout
Partition 0: 118293 bytes, 10000 lines, first line: 'Record 0: value=783'
Partition 1: 118293 bytes, 10000 lines, first line: 'Record 0: value=456'
Partition 2: 118293 bytes, 10000 lines, first line: 'Record 0: value=129'

How it works

The gzip.open() call wraps a file object that automatically compresses (mode 'wt') or decompresses (mode 'rt') text data using the gzip format. Writing lines with writelines() sends them to the compressed stream, and the file is closed immediately after the with block, ensuring the gzip footer is written. Reading back with gzip.open() and iterating lines decompresses on the fly, giving you exact counts and content without loading the whole file into memory. Using Path and the stat().st_size method gives the actual byte size of the compressed file on disk, which is useful for monitoring output size.

Common mistakes

  • Using 'w' mode without the 't' flag when writing text, causing a TypeError
  • Forgetting to close the file (not using `with`), leaving incomplete gzip data
  • Assuming gzip files can be read as plain text without `gzip.open()`
  • Not checking `st_size` after the file is fully written

Variations

  1. Use binary mode with bytes objects and `f.write()` instead of text lines
  2. Use `shutil.copyfileobj` with a compressed source for binary data
  3. Compress multiple partitions into a single tar.gz archive using `tarfile`

Real-world use cases

  • Writing output from a data pipeline (e.g., Spark jobs) into per-partition gzip files for efficient storage and transfer.
  • Generating compressed log files per shard in a distributed system, such as per-node logs shipped to object storage.
  • Storing partitioned CSV exports from a database for archival or downstream ETL processes.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Data pipelines & processing

Related tutorials and quizzes for this topic.