gpt4 book ai didi

python - 在 while 循环中使用生成器并在每次 yield 后进行评估

转载 作者:太空宇宙 更新时间:2023-11-04 02:04:19 25 4
gpt4 key购买 nike

我正在使用 Python 在 CAD 程序中打开一些文件。由于当我一次打开太多文件时程序会崩溃,因此我希望我的脚本在文件大小总和超过特定值时停止从我生成的列表中打开文件。

这是我目前所拥有的:

我正在将日志文件转换为列表。它包含以逗号分隔的文件路径:

fList = []

with open('C:/Users/user/Desktop/log.txt', 'r') as f:
fList = f.read().split(',')
with suppress(ValueError, AttributeError):
fList.remove('')
fcount = len(fList)

这是我用来迭代 partList 的生成器:

def partGenerator(partList):
for file in partList:
yield file

在这里,我尝试在文件大小总和小于 2500000 字节时遍历文件:

count = 0
progression = 0
storage = 0

while storage < 2500000:
for file in partGenerator(fList):
name = os.path.basename(file)
storage += os.path.getsize(file)
print(f'Auslastung: {storage} bite / 2500000 bite')
oDoc = oApp.Documents.Open(file)

progression += 1
percent = round(100 * progression / fcount)
print(f'Fortschritt: {progression} / {fcount} ({percent} %) - {name}')

发生的情况是,文件在 CAD 软件中正常打开,但在超过 while 条件后它们不会停止。我的猜测是,while 条件是在列表用完条目之后计算的,而不是像我想的那样在每个条目之后计算。

在正确语法方面的帮助会很棒!

我最终要寻找的是:

我想以一种打开一些文件的方式使用这个脚本,每当我在 CAD 程序中手动关闭一个文件时,它都会打开我列表中的下一个文件,直到列表用完。

最佳答案

你的 while 条件永远不会被检查,不,因为 for 循环永远不会让 Python 检查。 for 循环从生成器函数中获取元素既不存在也不存在。

如果您的条件仍然成立,您需要检查 inside 您的 for 循环:

for file in partGenerator(fList):
name = os.path.basename(file)
storage += os.path.getsize(file)
if storage >= 2500000:
# wait for input before continuing, then reset the storage amount
input("Please close some files to continue, then press ENTER")
storage = 0

Python 不会检查 while 条件,直到 while ...: 语句 block 中的完整套件(语句系列)完成运行或执行一个continue 语句,所以 while 条件真的不适合这里。

在上面的示例中,我使用了低技术含量的 input() 函数来要求运行脚本的人之后按 ENTER。这将取决于 oDoc.Documents 实际上作为 API 提供的内容,以查看您是否可以使用它来检测文件是否已关闭。

如果您想使用生成器函数,请让它跟踪文件大小。您甚至可以让它从 CSV 文件中读取这些内容。我会使用 csv module顺便说一句,处理 split 和进步:

import csv


def parts(logfile):
with open(logfile, newline='') as f:
reader = csv.reader(f)
files = [column for row in reader for column in row if column]
fcount = len(files)
storage = 0
for i, filename in enumerate(files):
storage += os.path.getsize(file)
if storage >= 2500000:
input("Please close some files to continue, then press ENTER")
storage = 0
print(f'Auslastung: {storage} bite / 2500000 bite')
yield file
print(f'Fortschritt: {i} / {fcount} ({i / fcount:.2%}) - {name}')

然后就用

for file in parts('C:/Users/user/Desktop/log.txt'):
oDoc = oApp.Documents.Open(file)

请注意,打开文件的绝对数量是操作系统限制的,而不是这些文件的大小。

关于python - 在 while 循环中使用生成器并在每次 yield 后进行评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55044294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com