![](/img/trans.png)
[英]Python: How to handle a corrupted gzip file in reading multiple files
[英]How to extract data from corrupted gzip files in python
我正在使用python gzip库扩展文件,其中一些已损坏。 确切的错误是这样的:
解压缩时出现错误-3:无效的块类型
是否可以读取文件断点之前的所有数据,或者以某种方式跳过断点并读取前后的内容? 压缩文件基本上是一行文本,我想恢复尽可能多的数据。
谢谢
希望有人觉得这有用:
# 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
您可以使用Python zlib接口一次解压缩一个片段,这将为您提供解压缩的数据,直到坏块为止。 请注意,损坏可能早于被捕获的位置,因此,在获取的解压缩数据的末尾可能会损坏一部分。
错误发生后几乎不可能恢复数据(请参阅问题注释中的链接),除非gzip文件经过专门准备具有恢复点。 gzip实用程序本身不这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.