The gzip module provides a file-like interface to GNU zip files, using zlib to compress and uncompress the data.

Writing Compresed Files


In [2]:
import gzip
import io
import os
outfilename = 'example.txt.gz'
with gzip.open(outfilename, 'wb') as output:
    with io.TextIOWrapper(output,encoding='utf-8') as enc:
        enc.write('Content of the example fiel to here.\n')
print(outfilename, 'contatins',os.stat(outfilename).st_size, 'bytes')


example.txt.gz contatins 75 bytes

In [3]:
os.system('file -b --mime {}'.format(outfilename))


Out[3]:
0

Reading Compressed Data


In [4]:
import gzip
import io
with gzip.open('example.txt.gz', 'rb') as input_file:
    with io.TextIOWrapper(input_file, encoding='utf-8') as dec:
        print(dec.read())


Content of the example fiel to here.