Last modified: Oct 14, 2024 By Alexander Williams

Python: Using os.listdir to List Files in a Directory

When working with directories in Python, the os module provides a convenient way to interact with the filesystem. One of its most commonly used methods is os.listdir(), which allows you to list all files and subdirectories within a specified directory. This article explains how to use os.listdir() with examples to help you navigate directories effectively.

1. What is os.listdir()?

The os.listdir() function returns a list of all files and directories in the specified path. If no path is specified, it lists the contents of the current working directory. Here’s the basic syntax:


import os

# List all files and directories in the current directory
files = os.listdir()
print(files)

This will print a list containing the names of files and directories in the current directory.

2. Listing Files in a Specific Directory

You can specify the path of the directory whose contents you want to list. For example:


import os

# List files and directories in a specified path
path = '/path/to/directory'
files = os.listdir(path)
print(files)

Replace /path/to/directory with the path of the directory you want to inspect. This will give you a list of all files and subdirectories in that location.

3. Filtering Files from the List

If you want to filter out only files or directories, you can use os.path along with os.listdir() to check if an item is a file or a directory:

Example: List Only Files


import os

path = '/path/to/directory'
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
print("Files:", files)

Example: List Only Directories


import os

path = '/path/to/directory'
directories = [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]
print("Directories:", directories)

These examples show how to filter the list to include only files or only directories, using os.path.isfile() and os.path.isdir().

4. Handling Errors with os.listdir()

If you try to list the contents of a directory that doesn’t exist, Python will raise a FileNotFoundError. To handle this, you can use a try and except block:


import os

path = '/non/existing/directory'
try:
    files = os.listdir(path)
    print(files)
except FileNotFoundError:
    print(f'The directory "{path}" does not exist.')

This example handles the error gracefully by printing a message if the specified directory does not exist.

5. Related Articles

If you’re looking to explore more about file and directory handling in Python, check out these articles:

Conclusion

The os.listdir() method is a powerful tool for working with files and directories in Python. Whether you’re listing all contents or filtering out files and directories, it provides a simple way to navigate through the filesystem. Understanding how to use this method effectively can help you automate and manage file-related tasks in your Python projects.