2017-01-18 1 views
0

2 개의 파일이 들어있는 zip 파일이 있습니다. zip 내의 각 파일 이름을 다른 변수로 설정해야합니다. 하지만 어떻게해야할지 모르겠습니다.Python을 사용하여 여러 파일의 압축을 풀고 포함 된 각 파일을 새 변수로 설정하십시오.

다음 코드는 두 파일을 모두 추출하고 두 파일 이름을 모두 나열하지만, ​​필자의 경우에는 압축을 푼 마지막 파일에서만 변수를 설정할 수 있습니다.

다음은 2 개의 파일이 포함 된 테스트 .zip에 대한 링크입니다. 하나 개의 파일은 "A"이고, 다른 파일은 "b.txt"입니다 : 그래도 그렇게하는 방법을 모르겠어요

filename1 = a 
filename2 = b.txt 

: http://www.fileconvoy.com/dfl.php?id=g676b9e355f65d84d9999232466917f2b06cc5d45e

내가 찾고 출력입니다. 여기 내 코드가있다.

#!/usr/bin/python 
outpath = '/home/ubuntu/untitled/' 
fn = 'myzipfile.zip' 

import zipfile 

fh = open(fn, 'rb') 
z = zipfile.ZipFile(fh) 

for name in z.namelist(): 
    z.extract(name, outpath) 
fh.close() 

file = zipfile.ZipFile(fn, "r") 
for info in file.infolist(): 
    print info.filename 
    filename = info.filename 

print "Extracted Filename: " + filename 



> a 
> b.txt 
> Extracted Filename b.txt 
나는 3 개 개의 파일이있는 .ZIP을 얻는 경우에, 나는 그것이은 filename1, filename2로 파일 이름 3 싶습니다 때문에

사람이 --- 어떻게 증가하는 변수 이름을 작성하는 저를 게재 할 수 있습니까?

감사

답변

0

당신은 당신이 원하는 어떤 이름의 파일에 압축 파일 객체를 복사 할 shutil.copyfileobj를 사용하여이 작업을 수행 할 수 있습니다.

import zipfile 
import shutil 

with zipfile.ZipFile('file_test.zip', 'r') as myfile: 
    target_names = ['filename1.txt', 'filename2.txt'] # names you want it to be 

    for item, name in zip(myfile.infolist(), target_names): 
     shutil.copyfileobj(myfile.open(item), open(name, 'w')) # copy extracted file object to a desired file 
     print 'The original file %s in zip file is now extracted and renamed to %s' % (item.filename, name) 
관련 문제