You can download this code by clicking the button below.
This code is now available for download.
This function recursively searches for files that match a given pattern in a specified directory and all its subdirectories, and returns a list of matching file paths.
Technology Stack : os, re
Code Type : Function
Code Difficulty : Intermediate
import os
import re
def find_files(start_path, file_pattern):
"""
Recursively find files matching a given pattern in a directory and its subdirectories.
:param start_path: The starting directory to search.
:param file_pattern: The pattern to match file names against.
:return: A list of file paths that match the pattern.
"""
matches = []
for root, dirs, files in os.walk(start_path):
for filename in files:
if re.match(file_pattern, filename):
matches.append(os.path.join(root, filename))
return matches