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

1 Answer

+1 vote
by (353k points)
selected by
Best answer

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

+5 votes
1 answer
+3 votes
1 answer
+3 votes
1 answer