【发布时间】:2018-11-27 14:32:04
【问题描述】:
我想找到尚不存在的第一个文件名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? 的主要答案中提到的那样,但我仍然想知道对于这种特殊情况是否有更好的方法(因此,它不是这个问题的欺骗)。
【问题讨论】:
-
glob.glob和一些regex可能是最好的选择。 -
明年会有一个不错的解决方案:python.org/dev/peps/pep-0572
标签: python loops while-loop code-duplication