Open In App

os.listdir() method-Python

Last Updated : 01 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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

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:

  • 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: 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)

Output
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

Output
Output

Explanation: This code lists only the files (excluding folders) in the specified directory by checking each entry with os.path.isfile().

Related articles


Next Article
Article Tags :
Practice Tags :

Similar Reads