python - zlib.error : Error -3 while decompressing: incorrect header check

标签 python gzip zlib

我有一个 gzip 文件,我正在尝试通过 Python 读取它,如下所示:

import zlib

do = zlib.decompressobj(16+zlib.MAX_WBITS)
fh = open('abc.gz', 'rb')
cdata = fh.read()
fh.close()
data = do.decompress(cdata)

它会抛出这个错误:

zlib.error: Error -3 while decompressing: incorrect header check

我该如何克服它?

最佳答案

你有这个错误:

zlib.error: Error -3 while decompressing: incorrect header check

这很可能是因为您正在尝试检查不存在的标题,例如您的数据遵循 RFC 1951(deflate 压缩格式)而不是 RFC 1950(zlib 压缩格式)或 RFC 1952(gzip 压缩格式)。

选择窗口位

但是 zlib 可以解压所有这些格式:

  • 要(去)压缩deflate格式,使用wbits = -zlib.MAX_WBITS
  • 要(去)压缩zlib格式,使用wbits = zlib.MAX_WBITS
  • 要(解)压缩 gzip 格式,使用 wbits = zlib.MAX_WBITS | 16

参见 http://www.zlib.net/manual.html#Advanced 中的文档(inflateInit2部分)

示例

测试数据:

>>> deflate_compress = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)
>>> zlib_compress = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS)
>>> gzip_compress = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)
>>> 
>>> text = '''test'''
>>> deflate_data = deflate_compress.compress(text) + deflate_compress.flush()
>>> zlib_data = zlib_compress.compress(text) + zlib_compress.flush()
>>> gzip_data = gzip_compress.compress(text) + gzip_compress.flush()
>>> 

zlib 的明显测试:

>>> zlib.decompress(zlib_data)
'test'

测试deflate:

>>> zlib.decompress(deflate_data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
zlib.error: Error -3 while decompressing data: incorrect header check
>>> zlib.decompress(deflate_data, -zlib.MAX_WBITS)
'test'

测试 gzip:

>>> zlib.decompress(gzip_data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
zlib.error: Error -3 while decompressing data: incorrect header check
>>> zlib.decompress(gzip_data, zlib.MAX_WBITS|16)
'test'

数据也兼容gzip模块:

>>> import gzip
>>> import StringIO
>>> fio = StringIO.StringIO(gzip_data)  # io.BytesIO for Python 3
>>> f = gzip.GzipFile(fileobj=fio)
>>> f.read()
'test'
>>> f.close()

自动 header 检测(zlib 或 gzip)

32 添加到 windowBits 将触发 header 检测

>>> zlib.decompress(gzip_data, zlib.MAX_WBITS|32)
'test'
>>> zlib.decompress(zlib_data, zlib.MAX_WBITS|32)
'test'

使用 gzip 代替

或者你可以忽略zlib,直接使用gzip模块;但是 please remember that under the hood , gzip 使用 zlib.

fh = gzip.open('abc.gz', 'rb')
cdata = fh.read()
fh.close()

关于python - zlib.error : Error -3 while decompressing: incorrect header check,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3122145/

相关文章:

python - HTML 中的 Web2py SQLFORM

Python 一个开源的单词列表,按价或类别进行比较

css - css文件中的属性顺序对其压缩有多大影响

gzip - 设置 zlib 以生成 gzip 压缩数据

c++ - 如何报告在 QuaGzipFile(QuaZIP 库)上读取数据的进度

python - 拆分名称列表,其中两个名字可能有共同的姓氏

python - 使用 Mercurial API 获取给定变更集的存储库变更

java - 使用 restclient 或 postman 发送 gzip 数据

python - 在 AWS Lambda Boto3 中写入 Gzip 文件

c++ - 如何使用 Crypto++ 解析 ZIP 文件?