4 Handy Ways to List Files in a Directory With Python
--
Do you want to find out how to list files in a directory using Python? In this article, you will see how to do it in 4 different ways so you can choose the one you prefer.
In all the examples we will list files in a directory with the following structure. We will call the directory test_dir:
├── data
│ └── tech.txt
└── report.txt
1 directory, 2 files
Let’s get started!
How to List Files in a Directory Using Python os.listdir()
The Python OS module allows the execution of Operating System tasks. This module comes with a variety of functions you can use to create, delete and fetch files and directories. The OS module has a function called listdir() which allows listing files and subdirectories in a directory.
Here is an example:
import os
directory = '/opt/codefather/test_dir/'
file_paths = os.listdir(directory)
print(file_paths)
After importing the OS module, we set the path to our directory and pass it to the listdir() function which lists all the files present in the directory.
Note that the listdir() function returns the list of files and subdirectories in the directory we pass to it, but it does not list files in any subdirectories.
In fact, as you can see, the output below doesn’t include the tech.txt file inside the data directory:
['report.txt', 'data']
Note: if you are using Windows you can set the value of the directory variable based on the location of the test_dir directory on your computer.
Let’s add the following Python statement before the last print() function to show the type of the file_paths variable.
print(type(file_paths))
When you execute the program you will see the following in the output that shows that the file_paths variable is a Python list.
<class 'list'>
From the output of os.listdir() we don’t know if a given element of the list returned by listdir() is a file or directory without doing any additional checks.