我有一个 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/