Skip to content
Advertisement

Nested if statement returns no such item

my scipt is working as in searching for zip files, unzip and do the things i want. But problem arise when i have nested zip files inside the zip file, so i thought maybe i copy the working if statement, make a few adjustments but i still cant get it to work.

print('Searching for ZipFiles')
for file in os.listdir(working_directory):
    zfile = file
    if zfile.endswith('.zip'):
        # Create a ZipFile Object and load sample.zip in it
        with ZipFile(zfile, 'r') as zipObj:
           # Get a list of all archived file names from the zip
           listOfFileNames = zipObj.namelist()
           # Iterate over the file names
           for fileName in listOfFileNames:
              zipObj.extract(fileName, './temp')
              maincom() #until here, my script is working, below is the new IF statement
              if fileName.endswith('.zip'):
                for file in os.listdir('.'):
                  zfile = file
                  if zfile.endswith('.zip'):
                  # Create a ZipFile Object and load sample.zip in it
                    with ZipFile(zfile, 'r') as zipObj:
                       # Get a list of all archived file names from the zip
                       listOfFileNames = zipObj.namelist()
                       # Iterate over the file names
                       for fileName in listOfFileNames:
                          zipObj.extract(fileName, '')
                          maincom()

what i want to achieve is to simply unzip the nested zip files in the current directory they are found, run maincom(), if possible, maybe delete the nested zip file after unzip completion

Thanks guys

Advertisement

Answer

Try this:

import glob
import zipfile

while len(glob.glob(working_directory+"*zip")) != 0:
    for filename in glob.glob(working_directory+"*zip"):
        with ZipFile(filename, 'r') as zipObj:
            for fileName in zipObj.namelist():
                zipObj.extract(fileName, './temp')
                maincom()

In principle, this will loop until there is no more zipfile in your working directory.

Which means: if zipfiles are present at iteration 1 and contain other zipfiles, those will be extracted. Which means: zipfiles will be present at iteration 2. And will be extracted. Etc Etc…

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement