- 1 year ago
Using Python to search specific file names in (sub)folders
To search for specific file names in a directory (including subdirectories) using Python, you can utilize the os
module and recursively iterate through the directory structure. Here's an example code that demonstrates this:
pythonimport os
def search_files(root_dir, file_names):
found_files = []
for root, dirs, files in os.walk(root_dir):
for file_name in files:
if file_name in file_names:
found_files.append(os.path.join(root, file_name))
return found_files
# Example usage
root_directory = 'path/to/directory' # Replace with the root directory you want to search
target_files = ['file1.txt', 'file2.txt'] # Replace with the file names you want to search for
result = search_files(root_directory, target_files)
print(result)
In this code, the search_files
function takes a root_dir
parameter which specifies the root directory to start the search from. It also takes a file_names
parameter which is a list of file names to search for. The function recursively walks through the directory tree using os.walk
and checks if each file name is in the list of target files. If a match is found, the file path is appended to the found_files
list.
You can modify the root_directory
and target_files
variables to suit your specific search requirements. The result
variable will contain a list of file paths that match the specified file names in the given directory and its subdirectories.