如何从python中损坏的gzip文件中提取数据

时间:2014-11-07 05:10:48

标签: python python-2.7 gzip zlib

我使用python gzip库来扩展文件,其中一些已损坏。确切的错误是:

解压缩时出错-3:无效块类型

是否可以在文件的断点之前读取所有数据,或者以某种方式跳过断点并阅读之前和之后的内容?压缩文件基本上是文本行,我想尽可能多地恢复数据。

由于

2 个答案:

答案 0 :(得分:4)

希望有人觉得这很有用:

# http://stackoverflow.com/questions/2423866/python-decompressing-gzip-chunk-by-chunk
# http://stackoverflow.com/questions/3122145/zlib-error-error-3-while-decompressing-incorrect-header-check/22310760
def read_corrupted_file(filename, CHUNKSIZE=1024):
    d = zlib.decompressobj(zlib.MAX_WBITS | 32)
    with open(filename, 'rb') as f:
        result_str = ''
        buffer=f.read(CHUNKSIZE)
        try:
            while buffer:
                result_str += d.decompress(buffer)
                buffer=f.read(CHUNKSIZE)
        except Exception as e:
            print 'Error: %s -> %s' % (filename, e.message)
        return result_str

答案 1 :(得分:2)

您可以使用Python zlib interface一次解压缩一块,这将为您提供解压缩的数据直至坏块。请注意,损坏可能在捕获点之前,因此您获得的解压缩数据末尾的某些数量可能已损坏。

在错误发生后几乎不可能恢复数据(请参阅评论中的链接),除非gzip文件是专门为恢复点准备的。 gzip实用程序本身并没有这样做。

相关问题