2015-01-20 35 views
1

我的目標是獲得一個txt文件,第二層zip文件。問題是,txt文件在所有的.zip的名稱相同,所以它覆蓋.txt和它只是這個運行後它抓住,我需要的.zip和提取物返回1 .TXTPython - 我試圖解壓縮一個文件,其中有多個zip文件

from ftplib import * 
import os, shutil, glob, zipfile, xlsxwriter 

ftps = FTP_TLS() 
ftps.connect(host='8.8.8.8', port=23) 
ftps.login(user='xxxxxxx', passwd='xxxxxxx') 
print ftps.getwelcome() 
print 'Access was granted' 
ftps.prot_p() 
ftps.cwd('DirectoryINeed') 
data = ftps.nlst() #Returns a list of .zip diles 
data.sort() #Sorts the thing out 
theFile = data[-2] #Its a .zip file #Stores the .zip i need to retrieve 
fileSize = ftps.size(theFile) #gets the size of the file 
print fileSize, 'bytes' #prints the size 

def grabFile(): 
    filename = 'the.zip' 
    localfile = open(filename, 'wb') 
    ftps.retrbinary('RETR ' + theFile, localfile.write) 
    ftps.quit() 
    localfile.close() 

def unzipping(): 
    zip_files = glob.glob('*.zip') 
    for zip_file in zip_files: 
     with zipfile.ZipFile(zip_file, 'r')as Z: 
      Z.extractall('anotherdirectory') 

grabFile() 
unzipping() 
lastUnzip() 

將內容添加到名爲anotherdirectory的文件夾中。它擁有第二層.zip。這是我陷入困境的地方。當我嘗試從每個壓縮文件中提取文件時。他們都有相同的名字。當我爲每個zip文件需要一個.txt時,我最終會得到一個.txt文件。

回答

1

我想你每次都指定相同的輸出目錄和文件名。在解壓縮功能,

變化

Z.extractall('anotherdirectory') 

Z.extractall(zip_file) 

Z.extractall('anotherdirectory' + zip_file) 

如果zip_file的都是一樣的,給每個輸出文件夾的唯一編號的名稱:解壓縮功能之前的 :

count = 1 

然後用此取代其他代碼:

Z.extractall('anotherdirectory/' + str(count)) 
count += 1 
+0

謝謝您的回答。該腳本將第一個.zip解壓縮並將它們放入「另一個目錄」中。 另一個目錄文件夾被創建。這個.zip有多個.zip。我可以迭代它們並檢索其中的.txt文件。我的問題是,所有.zip的'文件夾'名稱是相同的,它似乎是寫完它們。我試着做你的答案,但它仍然只返回一個.txt文件 > anotherdirectory>文件夾> name.txt <----該文本和文件夾在所有內容上都具有相同的名稱。 – Michael 2015-01-21 21:37:27

+0

查看我的答案更改。 – jeremydeanlakey 2015-01-22 00:30:46

+0

這很有道理。多謝,夥計!這種方法完美運作。我試圖給你的答案投票,但我需要先得到15分。萬分感激。 – Michael 2015-01-23 17:38:16

0

由於jeremydeanlakey的反應,我能得到我的腳本的這一部分。以下是我如何做到的:

folderUnzip = 'DirectoryYouNeed' 
zip_files = glob.glob('*.zip') 
count = 1 
for zip_file in zip_files: 
    with zipfile.ZipFile(zip_file, 'r') as Z: 
     Z.extractall(folderUnzip + '/' + str(count)) 
     count += 1 
相關問題