Get Gzip-compressed data on-memory

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.

Get compressed

>>> 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'

(Bonus) Try to unzip

>>> 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

Get Gzip-compressed data on-memory
Get structural data from CHEMBLID
Get Youtube data with python
Get Leap Motion data in Python.
Get data from Quandl in Python
Get the complete bitflyer tick data
Get Amazon data using Keep API # 1 Get data
Get data from Twitter using Tweepy
Get Splatoon 2 battle record data + bonus
Get additional data in LDAP with python
[Note] Get data from PostgreSQL with Python
Get Google Fit API data in Python
Get Youtube data in Python using Youtube Data API
Get data from an oscilloscope with pyVISA