Directory File Matcher with Regex

  • Share this:

Code introduction


This function searches for all files in a specified directory that match a given regular expression pattern.


Technology Stack : os, re

Code Type : File search

Code Difficulty : Intermediate


                
                    
import os
import re
import time
import random

def list_files_with_pattern(directory, pattern):
    """
    List all files in a directory that match a given pattern.

    Args:
        directory (str): The directory to search in.
        pattern (str): The pattern to match file names against.

    Returns:
        list: A list of file paths that match the pattern.
    """
    matching_files = []
    for root, dirs, files in os.walk(directory):
        for filename in files:
            if re.search(pattern, filename):
                matching_files.append(os.path.join(root, filename))
    return matching_files                
              
Tags: