[英]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.