![]() |
VOOZH | about |
os.listdir() method in Python is used to list all files and directories in a specified directory. If no directory is provided, it returns the contents of the current working directory.
This code shows how to list all files and folders from a given directory path.
Output
Explanation:
os.listdir(path='.')
Parameters: path (str, bytes or os.PathLike, optional) directory whose contents you want to list. Defaults to the current directory ('.') if not provided.
Returns: A list of strings, containing the names of files, directories, and links in the given directory.
Raises:
Example 1: This code displays all files and folders present in the current working directory.
Current directory contents: ['Solution.py', 'input.txt', 'output.txt', 'driver']
Explanation:
Example 2: This code tries to read a directory that does not exist and handles the error.
Output
Error: [Errno 2] No such file or directory: 'C:/Invalid/Path'
Explanation:
Example 3: This code lists only files and ignores folders inside a directory.
Output
Explanation: