Listing Files with Specific Extension in Directory and Subdirectories

  • Share this:

Code introduction


This function lists all files with a specified extension in the given directory and its subdirectories.


Technology Stack : Pathlib

Code Type : File Handling

Code Difficulty : Intermediate


                
                    
import random
from pathlib import Path

def list_files_with_extension(root_path, extension):
    """
    List all files in the given directory and its subdirectories that have the specified extension.

    Args:
        root_path (Path): The root directory to start the search from.
        extension (str): The file extension to filter by.

    Returns:
        list: A list of Path objects representing files with the given extension.
    """
    if not isinstance(root_path, Path):
        root_path = Path(root_path)

    if not root_path.is_dir():
        raise ValueError("The provided root_path is not a directory")

    matching_files = []
    for path in root_path.rglob(f'*{extension}'):
        if path.is_file():
            matching_files.append(path)

    return matching_files                
              
Tags: