2014-03-25 7 views
3

압축 된 데이터 파일 (폴더 안에 모두있는 다음 압축)이 있습니다. 압축을 풀지 않고 각 파일을 읽고 싶습니다. 몇 가지 방법을 시도했지만 아무 것도 zip 파일의 폴더를 입력하는 작동합니다. 어떻게해야합니까? zip 파일의 폴더없이Python의 압축 폴더에서 텍스트 파일을 읽는 방법

:

with zipfile.ZipFile('data.zip') as z: 
    for filename in z.namelist(): 
    data = filename.readlines() 

하나 개의 폴더로 :

with zipfile.ZipFile('data.zip') as z: 
     for filename in z.namelist(): 
     if filename.endswith('/'): 
      # Here is what I was stucked 

답변

10

namelist() 재귀 아카이브에있는 모든 항목의 목록을 반환합니다. 도움이

import os 
import zipfile 

with zipfile.ZipFile('archive.zip') as z: 
    for filename in z.namelist(): 
     if not os.path.isdir(filename): 
      # read the file 
      with z.open(filename) as f: 
       for line in f: 
        print line 

희망 :

당신은 항목이 os.path.isdir()를 호출하여 디렉토리인지 여부를 확인할 수 있습니다.

1

알렉의 코드가 작동합니다. 약간의 수정 작업을했습니다. (비밀번호로 보호 된 zip 파일에서는 작동하지 않습니다.)

import os 
import sys 
import zipfile 

z = zipfile.ZipFile(sys.argv[1]) # Flexibility with regard to zipfile 

for filename in z.namelist(): 
    if not os.path.isdir(filename): 
     # read the file 
     for line in z.open(filename): 
      print line 
     z.close()    # Close the file after opening it 
del z       # Cleanup (in case there's further work after this) 
관련 문제