The gzip module offers an interface similar to open(). You can process logs, CSV files, and archived responses line by line without loading all decompressed content into memory.
Practical example
import gzip
lines = ["id,name\n", "1,Ana\n", "2,Leo\n"]
with gzip.open("report.csv.gz", "wt", encoding="utf-8", newline="") as file:
file.writelines(lines)
with gzip.open("report.csv.gz", "rt", encoding="utf-8") as file:
print(file.readline().strip())
Text, bytes, and streaming
Use rt or wt with an encoding for text, and rb or wb for bytes. Iteration keeps memory predictable; an unbounded read() can remove that benefit.
Limits and integrity
Gzip compresses one stream rather than packaging a directory. Highly compressed input may expand dramatically, so enforce limits and handle BadGzipFile. Choose ZIP or TAR when you need a collection of files.
Keep learning
Continue with Python shutil: Copy, Move, and Archive Files and Python Pathlib: Complete Guide to File System Manipulation. A official Python documentation, accessed July 22, 2026, documents the API and behavior across versions.