[英]Extracting file from corrupted GZ
我的代码段可以将GZ中的文件另存为.txt文件,但有时该文件中可能包含一些奇怪的文本,导致提取模块崩溃。
我使用的方法:
def unpackgz(name ,path):
file = path + '\\' +name
outfilename = file[:-3]+".txt"
inF = gzip.open(file, 'rb')
outF = open(outfilename, 'wb')
outF.write( inF.read() )
inF.close()
outF.close()
我的问题我该如何解决? 可能类似于open(file,errors ='ignore')as fil:。 因为使用该方法,我只能提取正常文件。
编辑第一个问题
def read_corrupted_file(filename):
with gzip.open(filename, 'r') as f:
for line in f:
try:
string+=line
except Exception as e:
print(e)
return string
newfile = open("corrupted.txt", 'a+')
cwd = os.getcwd()
srtNameb="service"+str(46)+"b.gz"
localfilename3 = cwd +'\\'+srtNameb
newfile.write(read_corrupted_file(localfilename3))
导致多个错误: 像这样
固定为工作状态:
def read_corrupted_file(filename):
string=''
newfile = open("corrupted.txt", 'a+')
try:
with gzip.open(filename, 'rb') as f:
for line in f:
try:
newfile.write(line.decode('ascii'))
except Exception as e:
print(e)
except Exception as e:
print(e)
cwd = os.getcwd()
srtNameb="service"+str(46)+"b.gz"
localfilename3 = cwd +'\\'+srtNameb
read_corrupted_file(localfilename3)
print('done')
通常,如果文件已损坏,则尝试解压缩文件将引发错误,仅获取数据就无济于事,但是如果您想要停止崩溃,则可以使用try catch。
try:
pass
except Exception as error:
print(error)
应用此逻辑后,您可以使用gzip逐行读取,但有try异常,之后遇到损坏的部分时仍可以读取下一行。
import gzip
with gzip.open('input.gz','r') as f:
for line in f:
print('got line', line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.