2016-09-10 5 views
1

내 시스템에 10 개의 zip 파일이 들어있는 디렉토리가 있습니다. 각 zip 파일에는 텍스트 파일이 1 개 있습니다. 필자는 디렉토리의 모든 파일을 압축 해제 한 Python 스크립트를 작성한 다음 모든 결과 (압축 해제 된) 파일을 단일 파일로 연결합니다. 어떻게해야합니까? 지금까지 모든 파일의 압축을 풀고있는 스크립트가 있지만 연결을 추가하는 방법을 모르겠습니다. 아래는 내가 가지고있는 것입니다.Python 파일 압축 해제 및 결과 연결

import os, zipfile 

dir_name = '/path/to/dir' 
pattern = "my-pattern*.gz" 

os.chdir(dir_name) # change directory from working dir to dir with files 

for item in os.listdir(dir_name): # loop through items in dir 
    if item == pattern: # check for my pattern extension 
     file_name = os.path.abspath(item) # get full path of files 
     zip_ref = zipfile.ZipFile(file_name) # create zipfile object 
     zip_ref.extractall(dir_name) # extract file to dir 
     zip_ref.close() # close file 
+1

하는 http://stackoverflow.com/questions/5509872에서 많은 예를 들어 답변을 활용할 수 있어야한다 : 그래서, 당신은 연결 한 문자열을 제외하고 아무것도 필요하지 않습니다 가정하여 마지막 두 줄을 교체/python-append-multiple-files-in-given-order-to-one-big-file – dbmitch

답변

1

압축을 풀 때 파일을 디스크에 쓸 필요가 없습니다. 파이썬은 파일을 zip에서 직접 읽을 수 있습니다.

for zipfile in zip_ref.namelist(): 
    with open('targetfile', 'a') as target: 
     target.write(zip_ref.read(zipfile))