Search code examples
pythondirectoryos.walkpathname

Efficient way of finding a specific directory based on input parameters?


Given two parameters, 123 and abc, I can uniquely identify a directory of the form:

\path\to\unique_123\directory_abc

However, "unique" and "directory" will vary from folder to folder. I would like to create a function such that func(123, abc) returns \path\to\unique_123\directory_abc.

Is there something more efficient than using os.walk to accomplish this?


Solution

  • Possibly you want:

    import glob
    
    matches = glob.glob('**/*_%s/*_%s' % ('123', 'abc'), recursive=True)
    assert len(matches) == 1
    print(matches[0])
    

    But avoid recursive if you don't really need it, it will often be very slow! If you really do need it, I would probably shell out to find(1) which is better at this sort of thing.