发布时间:2019-08-12 09:52:11编辑:auto阅读(2805)
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(),加上之后就好了
上一篇: Python 2.7 和 Python
下一篇: python:链表定义以及实现
55070
41872
36464
31859
26768
26445
24980
20593
16516
15929
3121°
2829°
2922°
3077°
3008°
3281°
3172°
3010°
2995°
2981°