使用gzip d进行解压是可以的,但是在Python中使用zlib时是错误的

2024-04-25 07:51:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我下载了一个.gz文件,并使用“gzip-d”成功地解压缩了它。但是当我试图使用pythonzlib逐块解压缩时,它出错了。在

CHUNK = 1024 * 1024
infile = open('2019-07-06-13.log.gz')
d = zlib.decompressobj(32 + zlib.MAX_WBITS)
while True:
    chunk = infile.read(CHUNK)
    if not chunk:
        break
    data = d.decompress(chunk)
    print len(chunk), len(data)
print "#####"

因为文件很小,所以这个循环只运行一次。“len(data)”小于“len(chunk)”的打印结果肯定是错误的。在

输出:

^{pr2}$

同时,在我用gzip-c重新压缩我之前说过的用“gzip-d”创建的解压文件后,我用我的代码解压重新压缩的文件,结果镜头向右,这意味着我的代码对普通的gz文件很好用。在


Tags: 文件代码logdatalenopeninfileprint
2条回答

gzip格式与zlib格式不同:

Why does gzip give an error on a file I make with compress/deflate? The compress and deflate functions produce data in the zlib format, which is different and incompatible with the gzip format. The gz* functions in zlib on the other hand use the gzip format. Both the zlib and gzip formats use the same compressed data format internally, but have different headers and trailers around the compressed data. Source: zlib.net

为了解压缩.gz文件,您应该使用一个内置的gzip模块。在

谢谢大卫灵的提示!关键问题是源gz文件是由多个gz子文件串联而成的,这使得它的解压稍微复杂一些。在

解决方法如下:

 CHUNK = 1024 * 1024
 infile = open('2019-07-06-13.log.gz')
 d = zlib.decompressobj(32 + zlib.MAX_WBITS)

 while True:
    chunk = response.read(CHUNK)

    if not chunk:
           break

    data = d.decompress(chunk)
    print len(chunk), len(data)

    while d.unused_data != '':
       buf = d.unused_data
       d = zlib.decompressobj( zlib.MAX_WBITS |16)
       data = d.decompress(buf)
       print len(buf), len(data)

相关问题 更多 >

    热门问题