Skip to main content

How to list all files in a directory in Python

How to list all files in a directory in Python.

Here is a detailed step-by-step tutorial on how to list all files in a directory using Python.

Step 1: Import the necessary modules

First, we need to import the required modules in order to work with the file system in Python. We'll use the os module for this purpose.

import os

Step 2: Specify the directory path

Next, we need to provide the path to the directory for which we want to list all the files. You can either provide an absolute path or a relative path.

directory = '/path/to/directory'

Step 3: Use the os.listdir() function

To list all the files in a directory, we'll use the os.listdir() function. This function returns a list of all the files and directories present in the specified directory.

file_list = os.listdir(directory)

Step 4: Filter out directories from the file list

By default, the os.listdir() function returns both files and directories. If you only want to list files, you can filter out the directories from the file list using a loop.

file_list = [file for file in file_list if os.path.isfile(os.path.join(directory, file))]

Here, we use a list comprehension to iterate over each item in the file list. The os.path.isfile() function is used to check if an item is a file or not by joining the directory path with the item.

Step 5: Print the file list

Finally, we can print the list of files using a loop.

for file in file_list:
print(file)

This loop will iterate over each file in the file list and print its name.

Complete Example

Here's the complete example code that you can run:

import os

directory = '/path/to/directory'

file_list = os.listdir(directory)
file_list = [file for file in file_list if os.path.isfile(os.path.join(directory, file))]

for file in file_list:
print(file)

Make sure to replace /path/to/directory with the actual path of the directory you want to list the files for.

That's it! You now have a step-by-step tutorial on how to list all files in a directory using Python.