You can download this code by clicking the button below.
This code is now available for download.
This function is used to find all files that match a given pattern in a specified directory and its subdirectories. Here, the pattern is text files (files ending with .txt).
Technology Stack : os, re
Code Type : Function
Code Difficulty : Intermediate
import os
import json
import sys
import re
def find_files_in_directory(directory_path):
"""Find all files in a directory that match a given pattern.
Args:
directory_path (str): The path to the directory to search in.
Returns:
list: A list of file paths that match the pattern.
"""
matches = []
for root, dirs, files in os.walk(directory_path):
for file in files:
if re.match(r'.*\.txt$', file):
matches.append(os.path.join(root, file))
return matches