用Python如何解压缩缓冲区?

24

我有一段从库函数读取的字节缓冲区,我想解压内容(是一个单一的文本文件)。

我尝试使用zlib,但是我得到了这个错误:

>>> import zlib
>>> zlib.decompress(buffer)
error: Error -3 while decompressing data: incorrect header check

使用ZipFile可以实现,但需要使用临时文件:

import zipfile
f = open('foo.zip', 'wb')
f.write(buffer)
f.close()
z = ZipFile('foo.zip')
z.extractall()
z.close()
with open('foo.txt', 'r') as f:
    uncompressed_buffer = f.read()

是否可以使用zlib,如何避免使用临时文件?


你是否尝试过使用BytesIO对象而不是写入到磁盘? - Padraic Cunningham
使用 from zlib import decompress, MAX_WBITS; decompress(gz_bytes, 16 + MAX_WBITS) 即可完成。详见 这里 - bbayles
@bbayles 这个 incorrect header check 也遇到了同样的问题。 - nowox
@PadraicCunningham 这并没有帮助,因为我必须给ZipFile一个“filename”而不是一个文件指针。 - nowox
1
“zlib” 的 gzip 压缩和 “zipfile” 的 PKZIP 压缩是有区别的。我猜你用的是后者? - bbayles
显示剩余2条评论
1个回答

48

是否可以使用zlib?

不行,zlib不能用于ZIP文件。

如何避免使用临时文件?

使用io.BytesIO

import zipfile
import io

buffer = b'PK\x03\x04\n\x00\x00\x00\x00\x00\n\\\x88Gzzo\xed\x03\x00\x00\x00\x03\x00\x00\x00\x07\x00\x1c\x00foo.txtUT\t\x00\x03$\x14gV(\x14gVux\x0b\x00\x01\x041\x04\x00\x00\x041\x04\x00\x00hi\nPK\x01\x02\x1e\x03\n\x00\x00\x00\x00\x00\n\\\x88Gzzo\xed\x03\x00\x00\x00\x03\x00\x00\x00\x07\x00\x18\x00\x00\x00\x00\x00\x01\x00\x00\x00\xb4\x81\x00\x00\x00\x00foo.txtUT\x05\x00\x03$\x14gVux\x0b\x00\x01\x041\x04\x00\x00\x041\x04\x00\x00PK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00M\x00\x00\x00D\x00\x00\x00\x00\x00'

z = zipfile.ZipFile(io.BytesIO(buffer))

# The following three lines are alternatives. Use one of them
# according to your need:
foo = z.read('foo.txt')        # Reads the data from "foo.txt"
foo2 = z.read(z.infolist()[0]) # Reads the data from the first file
z.extractall()                 # Copies foo.txt to the filesystem

z.close()


print foo
print foo2

2
这将从ZIP中提取所有文件到文件系统中。如果您想从压缩文件中读取数据,请使用z.open()z.read() - Robᵩ
@Jarad - 谢谢。 - Robᵩ
1
你能否在“缓冲区”的一块上执行相同的操作,也就是说,在数据流上执行操作? - karelv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接