File Compression in Python

Compress a text file using the gzip module.

IntermediateFile Handling ProgramsExample 18 of 20
file-compression.py
1# Program to compress a text file using gzip
2
3import gzip
4
5src = input("Enter source text filename: ")
6dst = input("Enter destination gzip filename: ")
7
8try:
9 with open(src, "rb") as f_in, gzip.open(dst, "wb") as f_out:
10 f_out.writelines(f_in)
11 print("Compressed", src, "to", dst)
12except FileNotFoundError:
13 print("Source file not found.")

Output

Enter source text filename: notes.txt
Enter destination gzip filename: notes.txt.gz
Compressed notes.txt to notes.txt.gz

What's going on

gzip.open with 'wb' creates a gzip-compressed file; we stream bytes from the source file into it.

After this program

If the idea is still fuzzy, read Day 14: File Handling in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 file handling programs, or see every topic on Python exercises.