Finding Files by Pattern in Directory

  • Share this:

Code introduction


This function searches for files that match a specific pattern within a given directory and returns a list of paths to these files.


Technology Stack : os, re

Code Type : File matching function

Code Difficulty : Intermediate


                
                    
import os
import re

def list_files_with_pattern(directory, pattern):
    matches = []
    for root, dirs, files in os.walk(directory):
        for filename in files:
            if re.match(pattern, filename):
                matches.append(os.path.join(root, filename))
    return matches                
              
Tags: