How to list files in a directory in Python using os.listdir()?

Published on Aug. 22, 2023, 12:17 p.m.

You can use the os.listdir() method in Python to list all the files and directories in a specific directory. Here’s an example code snippet:

import os

folder_path = '/path/to/directory'

# List all the files and directories in the given path
content_list = os.listdir(folder_path)

# Output the list of contents
print(content_list)

This should output a list of all the files and directories in the specified directory path. If you want to list only the files you can use the following code snippet:

import os

folder_path = '/path/to/directory'

# List all the files in the given path
file_list = [
    f for f in os.listdir(folder_path)
    if os.path.isfile(os.path.join(folder_path, f))
]

# Output the list of files
print(file_list)

This code will only list the files in the specified directory path and exclude any directories that might be present within it. You can modify the condition in the list comprehension to include other filters as per your needs.

Keep in mind that os.listdir() only lists the contents of a directory and does not recurse into other directories within that directory. If you need to get a recursive listing of all the contents in a directory, you can look into using the os.walk() method instead.

Tags:

os