700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python利用gzip压缩解压缩StringIO

python利用gzip压缩解压缩StringIO

时间:2023-12-14 09:44:03

相关推荐

python利用gzip压缩解压缩StringIO

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。