首页 > 解决方案 > 嵌套 if 语句不返回此类项目

问题描述

我的 scipt 正在搜索 zip 文件、解压缩并做我想做的事情。但是当我在 zip 文件中嵌套了 zip 文件时出现了问题,所以我想也许我复制了工作 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 文件

多谢你们

标签: pythonpathzipunzip

解决方案


如果您的 zipfile 不是那么大,则无需将任何内容解压缩到磁盘,只需将内容保存在内存中,递归 zipfile 将使用zipobj.read(filename).

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)

我不知道您maincom()是否只会在最里面的 zipfile 或沿途的所有 zip 文件中运行。在示例中,它在所有 zip 文件中包含“foobar”的所有文件中运行。进行调整以使其按您的方式工作。

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


推荐阅读