Python os.listdir() Method

Usage

The os.listdir() is a widely used method in Python’s os module for listing the contents of a directory.

It returns a list containing the names of all entries (files and directories) in the specified directory. If no directory path is specified, it defaults to the current working directory.

Syntax

import os entries = os.listdir(path=’.’)

Parameters

ParameterConditionDescription
pathOptionalA string representing the path of the directory whose contents you want to list.
Default value is ‘.’ (current working directory)

Examples

Here’s a simple example of using os.listdir() to list the contents of a directory:

import os

# Specify the directory path
path = '/path/to/directory'

# List all entries in the specified directory
entries = os.listdir(path)

print(entries)
# Output: ['file1.txt', 'folder1', 'image.jpg', ...]

Note that if no directory path is specified, it defaults to the current working directory.

import os

# List all entries in the current directory
entries = os.listdir()

print(entries)
# Output: ['file1.py', ‘file.txt’]

Listing the Contents of the Parent Directory

To list all files and directories in the current working directory , you can pass . as the argument, whereas passing .. would list the contents of the parent directory, offering a convenient way to navigate file system hierarchies in Python.

import os

# List all entries in the parent directory
entries = os.listdir('..')

print(entries)
# Output: ['Scripts', 'Packages']

Distinguishing Files from Directories

As you can see, os.listdir() does not distinguish files from directories. It returns the names of both files and directories, mixed in a single list.

To distinguish files from directories, you can use os.path.isdir() or os.path.isfile().

import os

# Specify the directory path
path = '/path/to/directory'

# List all entries in the directory
entries = os.listdir(path)

for entry in entries:
    # Join the path and entry to get the full path
    full_path = os.path.join(path, entry)
    
    # Check if it's a file or directory
    if os.path.isfile(full_path):
        print(f"{entry} is a file.")
    elif os.path.isdir(full_path):
        print(f"{entry} is a directory.")

# Output:
# file1.txt is a file.
# folder1 is a directory.
# image.jpg is a file.

Handling Exceptions

os.listdir() can raise exceptions, most commonly FileNotFoundError if the specified path does not exist, PermissionError if there is insufficient permission to list the contents of the directory, or OSError for other file system-related errors.

So it’s good practice to use exception handling (try-except blocks) to deal with these potential errors.

import os

# Specify the directory path
path = '/path/to/directory'

try:
    # Attempt to list the contents of the specified directory
    entries = os.listdir(path)
    print(entries)

except FileNotFoundError:
    # Handle the case where the specified directory does not exist
    print(f"Error: The directory '{path}' does not exist.")

except PermissionError:
    # Handle the case where permission is denied
    print(f"Error: Permission denied to access the directory '{path}'.")

except OSError as error:
    # Handle other OS-related errors
    print(f"Error: An OS error occurred: {error}")