2011-10-22 5 views
4

다음 코드를 작성하여 압축 된 디렉토리의 텍스트 파일을 읽습니다. 출력을 바이트로 원하지 않기 때문에 출력을 문자열로 표시하기 위해 TextIOWrapper를 추가했습니다. Zip 파일을 줄 단위로 읽는 올바른 방법이라고 가정하면 (그렇지 않은 경우) 출력이 빈 줄을 인쇄하는 이유는 무엇입니까? 그것을 제거 할 수있는 방법이 있습니까?TextIOWrapper가있는 python zipfile 모듈

import zipfile 
import io 

def test(): 
    zf = zipfile.ZipFile(r'C:\Users\test\Desktop\zip1.zip') 
    for filename in zf.namelist(): 
     words = io.TextIOWrapper(zf.open(filename, 'r')) 
     for line in words: 
      print (line) 
    zf.close() 

test() 

>>> 
This is a test line... 

This is a test line... 
>>> 

The two lines in the file inside of the zipped folder are: 
This is a test line... 
This is a test line... 

고마워요!

답변

4

zipfile.open은 캐리지 리턴 (즉, '\ r')을 제거하지 않고 내 테스트에서 TextIOWrapper에 대한 기본값을 수행하지 않은 이진 모드로 압축 파일을 엽니 다. (즉 newline=None) 보편적 인 줄 바꿈을 사용하는 TextIOWrapper를 구성하십시오 :

import zipfile 
import io 

zf = zipfile.ZipFile('data/test_zip.zip') 
for filename in zf.namelist(): 
    with zf.open(filename, 'r') as f: 
     words = io.TextIOWrapper(f, newline=None) 
     for line in words: 
      print(repr(line)) 

출력 :

'This is a test line...\n' 
'This is a test line...' 

파이썬에서 라인별로 파일을 반복 정상적인 동작은 마지막에 줄 바꿈을 유지하는 것입니다. print 함수는 또한 개행을 추가하므로 빈 줄이 생깁니다. 그냥 파일을 인쇄하려면 대신 print(words.read())을 사용할 수 있습니다. 또는 print(line, end='') 인쇄 기능의 end 옵션을 사용할 수 있습니다.