Python 嵌套if语句不返回此类项

Python 嵌套if语句不返回此类项,python,path,zip,unzip,Python,Path,Zip,Unzip,我的scipt正在搜索zip文件,解压并做我想做的事情。但当我在zip文件中嵌套了zip文件时,问题就出现了,所以我想也许我复制了working if语句,做了一些调整,但我仍然无法让它工作 print('Searching for ZipFiles') for file in os.listdir(working_directory): zfile = file if zfile.endswith('.zip'): # Create a ZipFile Obje

我的scipt正在搜索zip文件,解压并做我想做的事情。但当我在zip文件中嵌套了zip文件时,问题就出现了,所以我想也许我复制了working if语句,做了一些调整,但我仍然无法让它工作

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()
我想要实现的是,只需在找到的当前目录中解压嵌套的zip文件,运行maincom(),如果可能的话,可以在解压完成后删除嵌套的zip文件

谢谢大家

试试这个:

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()
原则上,这将循环,直到您的工作目录中不再有zipfile


这意味着:如果zipfiles出现在迭代1中,并且包含其他zipfiles,那么这些zipfiles将被提取。这意味着:zipfiles将出现在迭代2中。并将被提取。等等。

如果你的ZipFile没有那么大,就不需要将任何东西解压缩到磁盘,只需将东西保存在内存中,递归ZipFile将使用zipobj.read(filename)返回的bytes对象链接起来

我不知道您的
maincom()
是只在最里面的zipfile中运行,还是在整个过程中在所有zip文件中运行。在本例中,它在所有zip文件中包含“foobar”的所有文件中运行。进行调整,使其按您的方式运行


BytesIO
用于将bytes对象转换为可查找的bytes对象,就像它是文件一样。

首先,我认为您应该学习使用递归。好的,让我来研究一下
import ZipFile
from io import BytesIO

def recursiveunziper(zipfile):
    with ZipFile(zipfile, 'r') as zipobj:
        for filename in zipobj.namelist():
            if filename.endswith('.zip'):
                recursiveunziper(BytesIO(zipobj.read(filename)))
            if filename.contains('foobar')
                maincom(zipobj.read(filename)) # sending bytes of foobar files to maincom

for filename in os.listdir(working_directory):
    if filename.endswith('.zip'):
        recursiveunziper(filename)