You can use gzip.GzipFile to perform Gzip compression with Python code, but if you do it normally, it will be output to a file. Use StringIO.StringIO(file-like object) to collect the output Gzip-compressed data.
↓ is done on Mac OS 10.10.1, Python2.7.11, utf-8. If the encoding etc. is different, the result will be slightly different.
>>> from gzip import GzipFile
>>> from StringIO import StringIO
>>> io = StringIO()
>>> with GzipFile(fileobj=io, mode='wb') as f:
... f.write('Data 1')
... f.write('Data 2')
... f.write('Data 3')
>>> io.getvalue()
'\x1f\x8b\x08\x00JM\rX\x02\xff{\xdc\xdc\xfe\xb8y\xcf\xe3\xa6\xfd\xef\xf7L|\x8c`OBbO\x06\x00\xb9M\x7f\xca$\x00\x00\x00'
>>> io = StringIO()
>>> io.write('\x1f\x8b\x08\x00JM\rX\x02\xff{\xdc\xdc\xfe\xb8y\xcf\xe3\xa6\xfd\xef\xf7L|\x8c`OBbO\x06\x00\xb9M\x7f\xca$\x00\x00\x00')
>>> io.seek(0)
>>> with GzipFile(fileobj=io, mode='rb') as f:
... print f.read()
Data 1 Data 2 Data 3
Recommended Posts