Python: Compress/Decompress Gzip Files

By Xah Lee. Date: . Last updated: .

Decompress gzip File

Here is a example of how to decompress a gzip file.

# -*- coding: utf-8 -*-
# python

# example of decompress a gzip file.

import gzip

inF = gzip.GzipFile("access_log.1.gz", 'rb')
s = inF.read()
inF.close()

outF = file("access_log.1", 'wb')
outF.write(s)
outF.close()

Compress gzip File

Here is a example of compressing a gzip file.

# -*- coding: utf-8 -*-
# python

# example of compressing a gzip file

import gzip

inF = file("x.txt", 'rb')
s = inF.read()
inF.close()

outF = gzip.GzipFile("x.txt.gz", 'wb')
outF.write(s)
outF.close()

12.2. gzip — Support for gzip files — Python v2.7.6 documentation