python利用gzip压缩解压缩StringIO

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(),加上之后就好了

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值