An elegant and short (pythonic) way to find the smallest unused number

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).

+4
source share
3 answers

The same number of statements, but perhaps a little more readable. Using : itertools.count

from itertools import count

def next_available(base):
    for ext in count(start=1):
        name = '{}.{:03d}'.format(base, ext)
        if not os.path.exists(name):
            return name
+3
source
import glob

used_filenames = {name:True for name in glob.glob('foo.[0-9][0-9][0-9]'))}

for i in range(1000):
    prospect = "foo.{:03d}".format(i)
    if prospect not in used_filenames:
        print("The next unused filename is", prospect)
        break
+1
source

Here is a suggestion:

import os
path = '/home/mydir'
existingnumbers = [int(entry.split('.')[1]) for entry in os.listdir(path) if 'foo.' in entry]
potentialnumbers = range(len(existingnumbers)+1)
newfile = 'foo.{0}'.format(min(set(potentialnumbers) - set(existingnumbers)))
0
source

Source: https://habr.com/ru/post/1629857/


All Articles