如何解压缩字节数组中的压缩数据?

如何解压缩字节数组中的压缩数据?,第1张

如何解压缩字节数组中的压缩数据

zlib.decompress(数据,15 + 32)应该自动检测是否有

gzip
数据或
zlib
数据。

zlib.decompress(data,15 + 16)应该在if

gzip
和barf if下工作
zlib

在Python 2.7.1中就是这样,创建一个gz小文件,将其读回并解压缩:

>>> import gzip, zlib>>> f = gzip.open('foo.gz', 'wb')>>> f.write(b"hello world")11>>> f.close()>>> c = open('foo.gz', 'rb').read()>>> c'x1fx8bx08x08x14xf4xdcMx02xfffoox00xcbHxcdxc9xc9W(xcf/xcaIx01x00x85x11Jrx0bx00x00x00'>>> ba = bytearray(c)>>> babytearray(b'x1fx8bx08x08x14xf4xdcMx02xfffoox00xcbHxcdxc9xc9W(xcf/xcaIx01x00x85x11Jrx0bx00x00x00')>>> zlib.decompress(ba, 15+32)Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: must be string or read-only buffer, not bytearray>>> zlib.decompress(bytes(ba), 15+32)'hello world'>>>

Python 3.x的用法非常相似。

*根据您正在运行Python 2.2.1的注释进行 *更新

叹。那甚至不是Python 2.2的最新版本。无论如何,继续

foo.gz
按上述创建的文件:

Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> strobj = open('foo.gz', 'rb').read()>>> strobj'x1fx8bx08x08x14xf4xdcMx02xfffoox00xcbHxcdxc9xc9W(xcf/xcaIx01x00x85x11Jrx0bx00x00x00'>>> import zlib>>> zlib.decompress(strobj, 15+32)Traceback (most recent call last):  File "<stdin>", line 1, in ?zlib.error: Error -2 while preparing to decompress data>>> zlib.decompress(strobj, 15+16)Traceback (most recent call last):  File "<stdin>", line 1, in ?zlib.error: Error -2 while preparing to decompress data# OK, we can't use the back door method. Plan B: use the # documented approach i.e. gzip.GzipFile with a file-like object.>>> import gzip, cStringIO>>> fileobj = cStringIO.StringIO(strobj)>>> gzf = gzip.GzipFile('dummy-name', 'rb', 9, fileobj)>>> gzf.read()'hello world'# Success. Now let's assume you have an array.array object-- which requires# premeditation; they aren't created accidentally!# The following pre assumes subtype 'B' but should work for any subtype.>>> import array, sys>>> aaB = array.array('B')>>> aaB.fromfile(open('foo.gz', 'rb'), sys.maxint)Traceback (most recent call last):  File "<stdin>", line 1, in ?EOFError: not enough items in file#### Don't panic, just read the fine manual>>> aaBarray('B', [31, 139, 8, 8, 20, 244, 220, 77, 2, 255, 102, 111, 111, 0, 203, 72, 205, 201, 201, 87, 40, 207, 47, 202, 73, 1, 0, 133, 17, 74, 13, 11, 0, 0, 0])>>> strobj2 = aaB.tostring()>>> strobj2 == strobj1 #### means True # You can make a str object and use that as above.# ... or you can plug it directly into StringIO:>>> gzip.GzipFile('dummy-name', 'rb', 9, cStringIO.StringIO(aaB)).read()'hello world'


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5668792.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存