List Files with Extension in Directory

  • Share this:

Code introduction


This function accepts a directory path and an optional file extension filter, returning a list of filenames in the directory that match the extension.


Technology Stack : Pathlib

Code Type : File list generator

Code Difficulty : Intermediate


                
                    
import random
from pathlib import Path

def list_files_in_directory(directory_path, extension=None):
    """
    List all files in a directory with an optional file extension filter.
    """
    if not isinstance(directory_path, Path):
        directory_path = Path(directory_path)
    if not directory_path.is_dir():
        raise ValueError("The provided path is not a directory.")

    files_list = []
    for file in directory_path.iterdir():
        if extension is None or file.suffix == extension:
            files_list.append(file.name)
    return files_list                
              
Tags: