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'
fin = open('data/inp.txt', 'r')
with gzip.open('data/inp.txt.gz', 'wb') as 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: