Finding Files with Specific Extension in Directory

  • Share this:

Code introduction


This function walks through the specified root directory and its subdirectories to find all files ending with a specified extension.


Technology Stack : os.walk() - Traverse the directory tree, os.path.join() - Concatenate paths

Code Type : File search

Code Difficulty : Intermediate


                
                    
import os
import re

def find_files_with_extension(root_dir, extension):
    for dirpath, _, filenames in os.walk(root_dir):
        for filename in filenames:
            if filename.endswith(extension):
                yield os.path.join(dirpath, filename)