Recursive File Listing with Extension

  • Share this:

Code introduction


This function recursively traverses the specified directory and its subdirectories, returning a list of all files with the specified extension.


Technology Stack : Pathlib, os.walk

Code Type : File list generator

Code Difficulty : Intermediate


                
                    
import random
from pathlib import Path

def list_files_recursive(directory, file_extension):
    """
    List all files with a given extension in a directory and its subdirectories.
    """
    if not isinstance(directory, Path):
        directory = Path(directory)
    if not directory.is_dir():
        raise ValueError("The provided directory does not exist or is not a directory.")

    files = []
    for root, dirs, filenames in os.walk(directory):
        for filename in filenames:
            if filename.endswith(file_extension):
                files.append(Path(root) / filename)
    return files