How do I list all files in a directory using Python?

Better Stack Team
Updated on January 26, 2023

To list all files in a directory in Python, you can use the os module and its listdir() function. This function returns a list of all the files and directories in the specified directory.

Here's an example of how you can use listdir() to list all files in a directory:

 
import os

# Get the list of all files in a directory
path = '/path/to/dir'
files = os.listdir(path)

# Print the files
for file in files:
    print(file)

This will print the names of all the files in the specified directory, including the files in any subdirectories.

If you only want to list the files in the top-level directory and not in any subdirectories, you can use the isdir() function from the os module to check if each item in the list is a directory or a file. Here's an example of how you can do this:

 
import os

# Get the list of all files in the directory
path = '/path/to/dir'
files = os.listdir(path)

# Print the files
for file in files:
    # Check if item is a file, not a directory
    if not os.path.isdir(os.path.join(path, file)):
        print(file)

This will print the names of all the files in the specified directory, but not the names of any subdirectories.