2017-12-02 169 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