Listing Files with Specific Extension in Directory and Subdirectories

  • Share this:

Code introduction


This function lists the names of all files with a specific extension in a directory and its subdirectories.


Technology Stack : glob, os

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import glob
import os

def list_files_with_extension(directory, extension):
    """
    List all files with a specific extension in a directory and its subdirectories.
    """
    pattern = f"{directory}/**/*.{'*'}{extension}", recursive=True)
    files = glob.glob(pattern)
    return [os.path.basename(file) for file in files]                
              
Tags: