0
0
PythonHow-ToBeginner · 3 min read

How to Decompress Gzip File in Python Quickly and Easily

To decompress a gzip file in Python, use the gzip module to open the file in read mode and then read its contents. You can write the decompressed data to a new file or process it directly in memory.
📐

Syntax

Use the gzip.open() function to open a gzip file. Specify the file path and mode ('rb' for reading binary). Then read the decompressed data with .read().

Example parts:

  • gzip.open('file.gz', 'rb'): Opens the gzip file for reading.
  • .read(): Reads the decompressed content.
  • with statement: Ensures the file is properly closed after reading.
python
import gzip

with gzip.open('file.gz', 'rb') as f:
    file_content = f.read()
💻

Example

This example shows how to decompress a gzip file named example.txt.gz and save the decompressed content to example.txt.

python
import gzip

input_path = 'example.txt.gz'
output_path = 'example.txt'

with gzip.open(input_path, 'rb') as f_in:
    with open(output_path, 'wb') as f_out:
        f_out.write(f_in.read())

print(f'Decompressed {input_path} to {output_path}')
Output
Decompressed example.txt.gz to example.txt
⚠️

Common Pitfalls

1. Opening gzip file in text mode: Always open gzip files in binary mode ('rb' or 'wb') to avoid errors.

2. Forgetting to close files: Use with to automatically close files and prevent resource leaks.

3. Reading large files at once: For very large files, read and write in chunks instead of loading all data at once.

python
import gzip

# Wrong way: opening in text mode (can cause errors)
# with gzip.open('file.gz', 'r') as f:
#     data = f.read()

# Right way: open in binary mode
with gzip.open('file.gz', 'rb') as f:
    data = f.read()
📊

Quick Reference

  • gzip.open(filename, 'rb'): Open gzip file for reading binary data.
  • gzip.open(filename, 'wb'): Open gzip file for writing compressed data.
  • Use with to manage file closing automatically.
  • Read or write data using .read() or .write().

Key Takeaways

Use the gzip module's open() with 'rb' mode to decompress gzip files safely.
Always use the with statement to handle file opening and closing automatically.
Avoid opening gzip files in text mode to prevent decoding errors.
For large files, read and write data in chunks to save memory.
Write decompressed data to a new file or process it directly in memory.