Skip to main content
 首页 » 编程设计

python之如何通过 while 循环以 python 方式避免此代码重复

2025年05月04日13haluo1

我想找到第一个不存在的文件名 myfile?????.txt(???? 是一个数字)。这有效:

import os 
i = 0 
f = 'myfile%04i.txt' % i 
while os.path.exists(f): 
    i += 1 
    f = 'myfile%04i.txt' % i 

但我不喜欢 f = ... 的代码重复。

是否有一种 pythonic 方法可以避免此 while 循环中的代码重复?

注意:我已经发布了一个半满意的解决方案,使用 do/while 成语,如 Emulate a do-while loop in Python? 的主要答案中所述,但我仍然想知道是否有针对这种特殊情况的更好方法(因此,这不是这个问题的骗局)。

请您参考如下方法:

你不需要在这里遵循 while 范式,一个带有 next() 的嵌套生成器表达式可以工作:

import os 
from itertools import count 
f = next(f for f in ('myfile%04i.txt' % i for i in count()) if not os.path.exists(f)) 
print(f)