Created
October 30, 2025 10:31
-
-
Save cd060/db08a215faff5c10ff43158ccab3622d to your computer and use it in GitHub Desktop.
Function for finding files with a specific name pattern in directories and sub directories
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def find_files(base, end_pattern, sub_name=None): | |
| ''' | |
| Searches for files with a specific name pattern | |
| in directories and subdirectories | |
| params: | |
| base : str | |
| strat directory | |
| end_pattern : list | |
| list of strings, patterns to find filenames | |
| sub_name : str | |
| name of sub dyrectories to search | |
| returns: | |
| paths_list : list | |
| list of strings, list of absolute paths to files | |
| ''' | |
| paths_list = [] | |
| for root, folder, files in os.walk(base): | |
| # --- case 1: files direct in base directory --- | |
| for file in files: | |
| if any(file.endswith(pattern) for pattern in end_pattern): | |
| paths_list.append(os.path.abspath(os.path.join(root, file))) | |
| # --- case 2: files in sub directory with specific name --- | |
| if sub_name: | |
| for sub_folder in folder: | |
| if sub_folder == sub_name: | |
| sub_path = os.path.join(root, sub_folder) | |
| for file in os.listdir(sub_path): | |
| if any(file.endswith(pattern) for pattern in end_pattern): | |
| paths_list.append(os.path.abspath(os.path.join(sub_path, file))) | |
| # --- case 3: files in any sub directory --- | |
| else: | |
| for sub_folder in folder: | |
| sub_path = os.path.join(root, sub_folder) | |
| for file in os.listdir(sub_path): | |
| if any(file.endswith(pattern) for pattern in end_pattern): | |
| paths_list.append(os.path.abspath(os.path.join(sub_path, file))) | |
| return paths_list |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment