LoginSignup
4
5

More than 5 years have passed since last update.

Gzip圧縮したデータをオンメモリで取得する

Posted at

gzip.GzipFile を使うとPythonコードでGzip圧縮ができますが、普通にやるとファイルに出力してしまいます。
StringIO.StringIO を使って、出力したGzip圧縮済みデータを回収します。

↓は Mac OS 10.10.1、Python2.7.11、utf-8 でやってます。
エンコーディング等異なるとちょっと結果も変わります。

圧縮して取得する

>>> from gzip import GzipFile
>>> from StringIO import StringIO

>>> io = StringIO()

>>> with GzipFile(fileobj=io, mode='wb') as f:
...     f.write('データ1')
...     f.write('データ2')
...     f.write('データ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()

データ1データ2データ3
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5