2017-05-19 5 views
1

Linux 서버에 많은 압축 파일이 있고 각 파일에는 여러 텍스트 파일이 있습니다.추출 된 파일의 이름을 zipfile로 바꿉니다.

내가 원하는 것은 압축 된 파일에서 같은 이름의 텍스트 파일을 추출하여 폴더에 저장하는 것입니다. 각 압축 파일에 대해 하나의 폴더를 만들고 텍스트 파일을 추출합니다. 파일 이름 끝에 부모 ZIP 폴더 이름을 추가하고 모든 텍스트 파일을 하나의 디렉토리에 저장해야합니다. 예를 들어 zip 폴더가 March132017.zip이고 holding.txt가 추출 된 경우 파일 이름은 holding_march13207.txt입니다.

제 문제는 추출한 파일의 이름을 변경할 수 없다는 것입니다. 조언을 해 주시면 감사하겠습니다.

import os 
import sys 
import zipfile 
os.chdir("/feeds/lipper/emaxx") 

pwkwd = "/feeds/lipper/emaxx" 

for item in os.listdir(pwkwd): # loop through items in dir 
    if item.endswith(".zip"): # check for ".zip" extension 
     file_name = os.path.abspath(item) # get full path of files 
     fh = open(file_name, "rb") 
     zip_ref = zipfile.ZipFile(fh) 

     filelist = 'ISSUERS.TXT' , 'SECMAST.TXT' , 'FUND.TXT' , 'HOLDING.TXT' 
     for name in filelist : 
      try: 
       outpath = "/SCRATCH/emaxx" + "/" + os.path.splitext(item)[0] 
       zip_ref.extract(name, outpath) 

      except KeyError: 
       {} 

     fh.close() 
+0

with..open을 사용한 다음 파일을 닫지 않아도됩니다. 또한 문자열과 경로를 연결하는 대신 os.path.join을 사용하는 것이 좋습니다 –

+1

이 코드는'pwkwd'가 현재 작업 디렉토리 인 경우에만 작동합니다. 그렇지 않으면'file_name = os.path.abspath (item)'은 올바른 경로를 구축하지 않습니다. 당신은 절대 경로가 필요 없다 ... os.path.join (pwkwd, item)'할 것이다. – tdelaney

+0

@ Matt.St 조언 주셔서 감사합니다 – Roo

답변

2

가 왜 그냥 문제의 파일을 읽고 추출의 그것을 너 자신을 대신 저장, 내가 '^^ 이제 창문에있어 테스트하지? 예 :

import os 
import zipfile 

source_dir = "/feeds/lipper/emaxx" # folder with zip files 
target_dir = "/SCRATCH/emaxx" # folder to save the extracted files 

# Are you sure your files names are capitalized in your zip files? 
filelist = ['ISSUERS.TXT', 'SECMAST.TXT', 'FUND.TXT', 'HOLDING.TXT'] 

for item in os.listdir(source_dir): # loop through items in dir 
    if item.endswith(".zip"): # check for ".zip" extension 
     file_path = os.path.join(source_dir, item) # get zip file path 
     with zipfile.ZipFile(file_path) as zf: # open the zip file 
      for target_file in filelist: # loop through the list of files to extract 
       if target_file in zf.namelist(): # check if the file exists in the archive 
        # generate the desired output name: 
        target_name = os.path.splitext(target_file)[0] + "_" + os.path.splitext(file_path)[0] + ".txt" 
        target_path = os.path.join(target_dir, target_name) # output path 
        with open(target_path, "w") as f: # open the output path for writing 
         f.write(zf.read(target_file)) # save the contents of the file in it 
       # next file from the list... 
    # next zip file... 
+0

해결책 주셔서 감사합니다! – Roo

0

각 파일의 압축이 풀린 후 간단히 이름 바꾸기를 실행할 수 있습니까? os.rename 트릭을해야합니다.

zip_ref.extract(name, outpath) 
parent_zip = os.path.basename(os.path.dirname(outpath)) + ".zip" 
new_file_name = os.path.splitext(os.path.basename(name))[0] # just the filename 

new_name_path = os.path.dirname(outpath) + os.sep + new_file_name + "_" + parent_zip 
os.rename(outpath, new_namepath) 

파일 이름의 경우 증분을 원하면 카운트를 시작하고 각 파일에 대해 on으로 이동하십시오. 당신이 마지막 이름을 신경 쓰지 않는 경우

count = 0 
for file in files: 
    count += 1 
    # ... Do our file actions 
    new_file_name = original_file_name + "_" + str(count) 
    # ... 

또는 당신은 항상 UUID 같은 것을 사용할 수 있습니다.

import uuid 
random_name = uuid.uuid4() 
+0

조언 해 주셔서 감사합니다! – Roo

1

파일을 추출하는 동안 파일 이름을 바꾸는 것이 가능하지 않습니까? 파일을 추출한 후 파일 이름 바꾸기는 어떻게됩니까? 리눅스 bash는 의지

, 당신은 한 줄에 그것을 달성 할 수

os.system("find "+outpath+" -name '*.txt' -exec echo mv {} `echo {} | sed s/.txt/"+zipName+".txt/` \;") 

그래서 먼저 우리가 계산 새 이름으로, 다음 이름 바꾸기 명령을 실행, 특정 폴더에있는 모든 TXT 파일을 검색 sed.

코드

+0

정말 고마워. 맞습니다. bash를 사용하면 항상 출구가됩니다 :-) – Roo