python - 嵌套 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 文件
多谢你们
解决方案
如果您的 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
字节对象转换为可查找字节对象,就像它是文件一样。
推荐阅读
- c# - Azure KeyVault:如何创建 clientId 和 clientSecret?
- oop - 这是否被视为程序编程(或贫血模式)?
- java - JPA 在每次迭代后开始消耗越来越多的内存
- android - Android Drawable XML 背景形状
- java - 更改允许在 Android 设备中使用的最大 Ram 一个应用程序的数量
- flutter - 按下按钮时播放 Flare 动画
- linux - Linux Ubuntu 中的 Bash shell 不启动可执行文件
- c# - 选择枚举时显示游戏对象的 Vector3
- asp.net-mvc - 宁静的服务请求/响应时间戳记录
- ios - 我可以编写一个像 Siri 这样支持启动指令检测的 iOS 应用吗?