How to Decompress a gzip File in Python
This code provides a function to decompress a .gz file, writing the decompressed content to a new file and returning the text, using the gzip standard library module.
Python code
28 linesimport gzip
from pathlib import Path
def decompress_gzip(filepath: str, output_path: str | None = None) -> str:
"""Decompress a .gz file and return the decompressed content."""
input_path = Path(filepath)
if output_path is None:
output_path = str(input_path.with_suffix(""))
with gzip.open(input_path, "rb") as f_in:
content = f_in.read()
with open(output_path, "wb") as f_out:
f_out.write(content)
return content.decode("utf-8")
if __name__ == "__main__":
# Create a sample gzip file for demonstration
sample_data = b"Hello, this is compressed gzip content!"
sample_gz = "sample.txt.gz"
with gzip.open(sample_gz, "wb") as f:
f.write(sample_data)
# Decompress it
result = decompress_gzip(sample_gz)
print(result)
Output
Hello, this is compressed gzip content!
How it works
The gzip.open function reads the compressed file in binary mode, then .read() returns the decompressed bytes. Writing those bytes to a file with open(output_path, 'wb') preserves the original content exactly. The default output path removes the .gz suffix, so sample.txt.gz becomes sample.txt. Finally, .decode('utf-8') converts the bytes to a string, assuming the original data was UTF-8 encoded. The function returns the content string for immediate use or inspection.
Common mistakes
- Forgetting to open the gzip file in binary mode ('rb') causing UnicodeDecodeError.
- Not decoding bytes before returning, leaving the caller with a bytes object.
- Overwriting an existing file without warning if the output path already exists.
Variations
- Use `gzip.open(output_path, 'wt', encoding='utf-8')` to write text directly instead of decoding manually.
- Stream large files in chunks to avoid loading everything into memory.
Real-world use cases
- Decompressing log files that are automatically gzipped by log rotation tools before analysis.
- Processing .gz-encoded data files downloaded from data.gov or other open-data portals.
- Reading compressed database backups or exported datasets for migration scripts.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.