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.

Easy Python 3.9+ Aug 9, 2026 Files & data 13 views 0 copies

Python code

28 lines
Python 3.9+
import 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

stdout
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

  1. Use `gzip.open(output_path, 'wt', encoding='utf-8')` to write text directly instead of decoding manually.
  2. 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

Run this sample

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

Open editor

More from Files & data

Related tutorials and quizzes for this topic.