Python-I';我正在尝试解压缩一个文件,其中包含多个zip文件
我的目标是得到一个包含第二层zip文件的txt文件。问题是txt文件在所有.zip文件中都有相同的名称,因此它会覆盖.txt,并且只返回1.txtPython-I';我正在尝试解压缩一个文件,其中包含多个zip文件,python,operating-system,zipfile,xlsxwriter,Python,Operating System,Zipfile,Xlsxwriter,我的目标是得到一个包含第二层zip文件的txt文件。问题是txt文件在所有.zip文件中都有相同的名称,因此它会覆盖.txt,并且只返回1.txt 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 ftp
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()
运行之后,它获取我需要的.zip文件,并将内容提取到名为anotherdirectory的文件夹中。第二层的拉链。这就是我遇到麻烦的地方。当我试图从每个zip提取文件时。他们都有相同的名字。当我需要一个用于每个zip的文件时,我会得到一个.txt文件 我认为您每次都指定了相同的输出目录和文件名。在解压功能中 改变
Z.extractall('anotherdirectory')
到
或
如果zip_文件都相同,请为每个输出文件夹指定一个唯一的编号名称:
解压功能之前:
count = 1
然后用以下代码替换其他代码:
Z.extractall('anotherdirectory/' + str(count))
count += 1
多亏了Jeremydeanakey的回应,我才能够得到我剧本的这一部分。我是这样做的:
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
谢谢你的回答。该脚本正确地解压第一个.zip文件,并将其放入“anotherdirectory”中。将创建另一个目录文件夹。这个.zip有多个.zip。我可以遍历它们,并在其中检索.txt文件。我的问题是所有.zip的“文件夹”名称都是相同的,似乎写得太多了。我试着做了你的答案,但它仍然只返回一个.txt文件>另一个目录>文件夹>name.txt查看对我答案的更改。这很有意义。谢谢你,伙计!这种方法非常有效。我想投票支持你的答案,但我需要先得到15分。非常感谢。
Z.extractall('anotherdirectory/' + str(count))
count += 1
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