Listing Files in a Directory

  • Share this:

Code introduction


This function is used to list all files in a specified directory.


Technology Stack : os, re, sys, time

Code Type : Function

Code Difficulty : Intermediate


                
                    
import os
import re
import sys
import time

def list_files_in_directory(directory_path):
    """
    List all files in a given directory.

    Args:
    directory_path (str): The path to the directory.

    Returns:
    list: A list of file names in the directory.
    """
    if not os.path.isdir(directory_path):
        raise ValueError("The provided path is not a directory.")
    
    try:
        return [file for file in os.listdir(directory_path) if os.path.isfile(os.path.join(directory_path, file))]
    except Exception as e:
        raise IOError(f"Failed to list files in directory: {str(e)}")                
              
Tags: