codycrossley
codycrossley

Reputation: 611

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?

Upvotes: 0

Views: 33

Answers (2)

o11c
o11c

Reputation: 16066

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.

Upvotes: 2

touch my body
touch my body

Reputation: 1723

If you want to see what directories are in folder, use:

os.listdir("/path/to/folder")

Using this, you can get the names of the subfolders.

If you see a folder like unique_123 already in there, you can strip the digits off the end of the folder name using `rstrip("1234567890") on the string, assuming that the folder name ends in digits and you need to replace them .

Upvotes: -1

Related Questions