Suppose I write a file with the name foo.001, but 001is replaced with the lowest free index based on the files that actually exist. What is the most elegant way to write this? This is what I use, but it doesn’t look very good, does it?
base='foo'
i=0
while True:
i+=1; name=base+'.%03d'%i
if not os.path.exists(name): break
# use name here
Best deals are welcome.
EDIT: the search will not run in parallel, plus I need the lowest unused index (parallel searches will not always give the lowest). Also suppose that I cannot list all the names that have already been used, only check if one exists (I would like to use it not only for files, but for named objects in general, and the list is not always possible or effective).
source
share