![]() |
Finding directory based on wildcard? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Finding directory based on wildcard? (/thread-9704.html) |
Finding directory based on wildcard? - jkimrey - Apr-24-2018 Hi. I'm trying to create a function that will return a (windows) directory based on a wildcard. For instance, my starting directory is C:\users\auser, and I would like to search through all (sub) directories under this directory and return any directory names that contain '*gain*' in the directory name. Any advice would be appreciated. Thanks. RE: Finding directory based on wildcard? - mlieqo - Apr-24-2018 maybe something like this: import os def search_dir(starting_directory, string_to_search): directory_list = [] for directory in [x[0] for x in os.walk(starting_directory)]: if string_to_search in os.path.basename(os.path.normpath(directory)): directory_list.append(directory) return directory_list starting directory for you can be 'C:\users\auser' and string to search f.e. '*gain*' RE: Finding directory based on wildcard? - jkimrey - Apr-24-2018 (Apr-24-2018, 01:41 PM)mlieqo Wrote: maybe something like this: That's excellent - thank you for the help! Now I want to make sure I handle exceptions correctly. IE - there should always only be one directory returned. What would be the "correct" way to return an error if the len(directory_list) <> 1? Thanks again. RE: Finding directory based on wildcard? - Gribouillis - Apr-24-2018 Have you considered using glob.glob() ?
RE: Finding directory based on wildcard? - mlieqo - Apr-25-2018 (Apr-24-2018, 02:20 PM)jkimrey Wrote: Now I want to make sure I handle exceptions correctly. IE - there should always only be one directory returned. What would be the "correct" way to return an error if the len(directory_list) <> 1?Well you can add another if statement and raise error if your len(directory_list) is not equal to 1, or simply just add assert statement before return - not sure exactly what is the 'correct' way. And also maybe think about doing it outside of the function, maybe you will want to have the list longer in some cases. |