如何通过while循环以pythonically方式避免这种代码重复?

2024-05-26 11:08:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

但是我不喜欢f = ...的代码重复。你知道吗

在这个while循环中有没有一种pythonic方法来避免代码重复?

注意:我已经发布了一个半满意的解决方案,使用了do/while的习惯用法,正如Emulate a do-while loop in Python?的主要答案中提到的,但是我仍然想知道是否有更好的方法来解决这个特殊的情况(因此,这不是这个问题的一个重复)。你知道吗


Tags: path方法代码importtxtos文件名exists
3条回答

在写问题的结尾时,我几乎找到了答案。经过一些修改后,它可以工作:

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

我仍然想知道是否有一种更具python风格的方法,可能是使用迭代器、生成器、next(...)或类似的东西。你知道吗

去掉f变量。你知道吗

import os

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

您不需要遵循这里的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)

相关问题 更多 >