When working with a data stream instead of a file, use the GzipFileclass directly to compress or uncompress it. This is useful when thedata is being transmitted over a socket or from read an existing(already open) file handle. A StringIO buffer can also be used.
Note
When re-reading the previously compressed data, I pass an explicit length toread(). Leaving the length off resulted in a CRC error, possibly becauseStringIO returned an empty string before reporting EOF. If you areworking with streams of compressed data, you may want to prefix the data withan integer representing the actual amount of data to be read.
我按照他的方法,自己写了一下:
>>> import gzip
>>> from cStringIO import StringIO
>>> puredata = 'test'
>>> buf=StringIO()
>>> f=gzip.GzipFile(mode="wb", fileobj=buf)
>>> f.write(puredata)
4
>>> f.close()
>>> cdata = buf.getvalue()
>>> print cdata
ヒ
>>> print len(cdata)
24
>>> import binascii
>>> print binascii.hexlify(cdata)
1f8b0800e0a3ab4f02ff2b492d2e01000c7e7fd804000000
>>> inbuffer = StringIO(cdata)
>>> f = gzip.GzipFile(mode="rb", fileobj=inbuffer)
>>> rdata = f.read()
>>> print rdata
test
成功
之前压缩完了之后总是解压缩不成,提示:
IOError: CRC check failed 0xab380008L != 0x0L
后来发现没有调用f.close(),加上之后就好了