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.
import os
path = "your_directory_path"
contents = os.listdir(path)
print("Directory contents:", contents)
Output

Explanation:
- import os loads the operating system module.
- os.listdir(path) reads all file and folder names from the given path.
- contents stores the list of directory items.
Syntax
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:
- FileNotFoundError: if the specified path does not exist.
- NotADirectoryError: if the specified path is not a directory.
- PermissionError: if the program does not have permission to access the directory.
Examples
Example 1: This code displays all files and folders present in the current working directory.
import os
contents = os.listdir()
print("Current directory contents:", contents)
Output
Current directory contents: ['Solution.py', 'input.txt', 'output.txt', 'driver']
Explanation:
- os.listdir() without a path uses the current folder.
- All file and folder names from that directory are returned as a list.
Example 2: This code tries to read a directory that does not exist and handles the error.
import os
path = "C:/Invalid/Path"
try:
print(os.listdir(path))
except OSError as e:
print("Error:", e)
Output
Error: [Errno 2] No such file or directory: 'C:/Invalid/Path'
Explanation:
- os.listdir(path) attempts to open the given directory.
- If the folder does not exist, Python raises an error.
- The try-except block catches the error and prints a friendly message.
Example 3: This code lists only files and ignores folders inside a directory.
import os
path = "your_directory_path"
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
print("Only files:", files)
Output

Explanation:
- os.listdir(path) gets all items from the directory.
- os.path.join() builds the full file path.
- os.path.isfile() checks whether the item is a file.
- Only file names are kept in the final list and printed.