1
我的代码片段可以从GZ中提取文件,并将其保存为.txt文件,但有时该文件可能包含一些会导致崩溃提取模块的奇怪文本。从损坏的GZ中提取文件
方法我用:
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(文件,错误='ignore')为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))
结果在多个错误: Like This
固定到工作状态:
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')
那么,该文件包含我需要得到的一些信息。它可能在文件中间有几行,其他的都可以。 – Gerard
您可以使用try-line逐行读取吗? –
编辑试题 – Gerard