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.
Python code
37 linesimport 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
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
- Use binary mode with bytes objects and `f.write()` instead of text lines
- Use `shutil.copyfileobj` with a compressed source for binary data
- 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
More from Data pipelines & processing
- Add a UUID Surrogate Key to Each Row in a CSV with Python easy
- Attach Source File Metadata to Records in Python easy
- Build a Python Utility That Detects Duplicate Records Across Multiple Excel Sheets medium
- Check Null Rate Threshold in PySpark DataFrame medium
- Count Records Processed per Category in Python easy
- Create Data Helper Functions in Python for Beginners easy
Keep learning
Related tutorials and quizzes for this topic.