File Compression

Compress a text file using the gzip module.

IntermediateTopic: File Handling Programs
Back

Python File Compression Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# Program to compress a text file using gzip

import gzip

src = input("Enter source text filename: ")
dst = input("Enter destination gzip filename: ")

try:
    with open(src, "rb") as f_in, gzip.open(dst, "wb") as f_out:
        f_out.writelines(f_in)
    print("Compressed", src, "to", dst)
except FileNotFoundError:
    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

Understanding File Compression

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

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents