File Matching with Regex in Directory Tree

  • Share this:

Code introduction


This function takes a directory path and a regular expression pattern as arguments, and returns a list of file paths that match the pattern.


Technology Stack : os, re

Code Type : Function

Code Difficulty : Intermediate


                
                    
import os
import re
import sys
import time

def find_files(root_dir):
    """
    Recursively find all files in a directory and its subdirectories.

    Args:
        root_dir (str): The root directory to start the search from.

    Returns:
        list: A list of file paths found.
    """
    file_list = []
    for dirpath, dirnames, filenames in os.walk(root_dir):
        for f in filenames:
            file_path = os.path.join(dirpath, f)
            file_list.append(file_path)
    return file_list

def xxx(arg1, arg2):
    """
    Find files in a directory and its subdirectories that match a specific pattern.

    Args:
        root_dir (str): The root directory to start the search from.
        pattern (str): The regex pattern to match file names.

    Returns:
        list: A list of file paths that match the pattern.
    """
    if not os.path.isdir(root_dir):
        raise ValueError("root_dir must be a valid directory.")
    if not isinstance(pattern, str):
        raise ValueError("pattern must be a string.")

    file_paths = find_files(root_dir)
    matched_files = [f for f in file_paths if re.match(pattern, os.path.basename(f))]

    return matched_files

# Example usage:
# matched_files = xxx("/path/to/search", "*.txt")
# print(matched_files)                
              
Tags: