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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github