2017-12-02 166 views
1

我的代碼片段可以從GZ中提取文件,並將其保存爲.txt文件,但有時該文件可能包含一些會導致崩潰提取模塊的奇怪文本。從損壞的GZ中提取文件

Some Gibberish from file:

方法我用:

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') 

回答

0

一般來說,如果該文件已損壞,然後它會拋出嘗試解壓文件時出錯,沒有多少可以簡單地對s進行操作直到獲得數據,但如果你只是想阻止它崩潰,你可以使用try catch。

try: 
    pass 
except Exception as error: 
    print(error) 

運用這一邏輯,你可以通過閱讀用gzip線線,與一試例外,之後,還在讀書的下一行,當它擊中損壞的部分。

import gzip 

with gzip.open('input.gz','r') as f: 
    for line in f: 
    print('got line', line) 
+0

那麼,該文件包含我需要得到的一些信息。它可能在文件中間有幾行,其他的都可以。 – Gerard

+0

您可以使用try-line逐行讀取嗎? –

+0

編輯試題 – Gerard