List Files in Directory with Path Object

  • Share this:

Code introduction


This function accepts a Path object as an argument and returns a list of all files in the specified directory. If the provided path is not a directory, it raises a ValueError.


Technology Stack : Pathlib

Code Type : Function

Code Difficulty : Intermediate


                
                    
from pathlib import Path
import random

def list_files_in_directory(directory_path: Path):
    """
    List all files in the given directory path.
    """
    if not directory_path.is_dir():
        raise ValueError("The provided path is not a directory.")
    
    file_list = [file for file in directory_path.iterdir() if file.is_file()]
    return file_list                
              
Tags: