Michael
Michael

Reputation: 11

Python - I'm trying to unzip a file that has multiple zip files within

My goal is to get to a txt file that is withing the second layer of zip files. The issue is that the txt file has the same name in all the .zip, so it overwrites the .txt and it only returns 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 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()

After this runs it grabs the .zip that I need and extracts the contents to a folder named anotherdirectory. Where it holds the second tier of .zips. This is where I get into trouble. When I try to extract the files from each zip. They all share the same name. I end up with a single .txt when I need one for each zip.

Upvotes: 1

Views: 1115

Answers (2)

Michael
Michael

Reputation: 11

Thanks to jeremydeanlakey's response, I was able to get this part of my script. Here is how I did it:

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

Upvotes: 0

jeremydeanlakey
jeremydeanlakey

Reputation: 153

I think you're specifying the same output directory and filename each time. In the unzipping function,

change

Z.extractall('anotherdirectory')

to

Z.extractall(zip_file)

or

Z.extractall('anotherdirectory' + zip_file)

if the zip_file's are all the same, give each output folder a unique numbered name: before unzipping function:

count = 1

then replace the other code with this:

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

Upvotes: 1

Related Questions