Search code examples
pythonloopswhile-loopcode-duplication

How to pythonically avoid this code duplication with a while loop?


I want to find the first filename myfile????.txt that doesn't exist yet (???? is a number). This works:

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

but I don't like the code duplication of f = ....

Is there a pythonic way to avoid the code duplication in this while loop?

NB: I have posted a half-satisfactory solution, using a do/while idiom, as mentioned in the main answer of Emulate a do-while loop in Python?, but I still wonder if there is better way for this particular case (thus, it's not a dupe of this question).


Solution

  • You do not need to follow the while paradiagm here, a nested generator expression with next() works:

    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)