+2 votes
in Programming Languages by (51.1k points)
I want to compress an existing file in the gzip format (.gz). How can I do it in Python?

1 Answer

0 votes
by (157k points)

You can use gzip and shutil libraries of Python to compress a file. Here is an example.

I am compressing my input text file 'inp.txt'

import gzip
import shutil
fin = open('data/inp.txt', 'r')
with gzip.open('data/inp.txt.gz', 'wb') as fout:
    shutil.copyfileobj(fin, fout)

To unzip and read the content of the gzipped file, you can use the following code:

with gzip.open('data/inp.txt.gz', 'rb') as f:
    for line in f:

Related questions