2017-12-02 1 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() 

내 질문은 내가이 문제를 갈 수 있습니까? 파일명이 인 과 비슷한 파일 (파일, 오류 = '무시')이있을 수 있습니다. 그 방법으로 나는 건강한 파일 만 추출 할 수 있기 때문에. 여러 오류에 첫 번째 질문에 대한

편집

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

답변

0

일반적 경우 다음이 발생합니다 : 작업 상태로 고정 Like This

파일을 압축 해제하는 중 오류가 발생했습니다. 간단히 할 수있는 일이 많지 않습니다. 데이터를 가져올 때까지 멈추고 싶다면 try catch를 사용할 수 있습니다. 시도 예외 당신이 gzip으로 라인으로 라인을 읽을 수이 논리를 적용

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

후, 여전히 다음 줄을 읽는 것은 손상된 부분을 칠 때.

import gzip 

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

음, 해당 파일에는 필요한 몇 가지 정보가 포함되어 있습니다. 그것은 파일의 중간에 몇 줄이 있고 나머지는 괜찮을 수도 있습니다. – Gerard

+0

try를 사용하여 한 줄씩 읽을 수 있습니까? –

+0

그 질문에 편집 된 질문 – Gerard