Last Updated : 01 Jul, 2025
os.listdir() method in Python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then a list of files and directories in the current working directory will be returned. Example:
Python
import os
path = "C:/Users/GFG0578/Documents"
contents = os.listdir(path)
print("Directory contents:", contents)
Output
Explanation: This code lists all files and folders in the specified Documents directory.
Syntax of os.listdir()os.listdir(path='.')
Parameters: path (str, bytes or os.PathLike, optional) is the directory whose contents you want to list. Defaults to the current directory ('.') if not provided.
Returns: A list containing the names of entries (files, subdirectories, links, etc.) in the given directory. The names are returned as strings.
Raises:
Example 1: List contents of the current directory
Python
import os
contents = os.listdir()
print("Current directory contents:", contents)
Output
Current directory contents: ['example.py']
Explanation: When no path is provided, os.listdir() defaults to the current working directory .
Example 2: Handling errors if the path is invalid
Python
import os
path = "C:/Invalid/Path"
try:
print(os.listdir(path))
except OSError as e:
print("Error:", e)
Error: [Errno 2] No such file or directory: 'C:/Invalid/Path'
Explanation: This code tries to list the contents of a non-existent directory. The try-except block catches any error like FileNotFoundError or PermissionError and prints it.
Example 3: Filter only files in a directory
Python
import os
path = "C:/Users/GFG0578/Documents"
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
print("Only files:", files)
Output
OutputExplanation: This code lists only the files (excluding folders) in the specified directory by checking each entry with os.path.isfile().
Related articles
Python | os.listdir() method
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4