Does Python have any built-in functionality to add a number to a filename if it already exists?
My idea is that it would work the way certain OS\'s work - if a file
Let's say I already have those files:
This function generates the next available non-already-existing filename, by adding a _1, _2, _3, etc. suffix before the extension if necessary:
import os
def nextnonexistent(f):
fnew = f
root, ext = os.path.splitext(f)
i = 0
while os.path.exists(fnew):
i += 1
fnew = '%s_%i%s' % (root, i, ext)
return fnew
print(nextnonexistent('foo.txt')) # foo_3.txt
print(nextnonexistent('bar.txt')) # bar_1.txt
print(nextnonexistent('baz.txt')) # baz.txt