【问题标题】:Unzip buffer with Python?用 Python 解压缓冲区?
【发布时间】:2016-03-13 17:38:15
【问题描述】:

我有一个从库调用中读取的字节缓冲区,我想解压缩作为单个文本文件的内容。

我尝试使用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 对象而不是写入磁盘
  • from zlib import decompress, MAX_WBITS; decompress(gz_bytes, 16 + MAX_WBITS) 会做到的。另请参阅here
  • @bbayles 这个incorrect header check也有同样的问题
  • @PadraicCunningham 这没有帮助,因为我必须给filenameZipFile 而不是文件指针
  • zlib 的 gzip 压缩和 zipfile 的 PKZIP 压缩之间存在差异。我猜你是后者?

标签: python zip zlib unzip zipfile


【解决方案1】:

可以用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

【讨论】:

  • 这会将 ZIP 中的所有文件提取到文件系统中。如果要从压缩文件中读取数据,请使用z.open()z.read()
  • @Jarad - 谢谢。
  • 你能在一块“缓冲区”上也这样做吗?这么说是在数据流上?
猜你喜欢
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 2021-05-14
相关资源
最近更新 更多