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