Python

Python os listdir

Sometimes you may need to list the files and directories in a folder/directory. For example, you may want to find a file by its name, but you do not know which folder it is in. To do this you can use a command or a program that searches the destination folder for the file. In Python, the “os.listdir()” method of the os module is used to list all the files and directories by taking the particular path as an argument.

This blog provides a comprehensive tutorial on Python’s “os.listdir()” method utilizing several examples. Follow the below outline:

What is the “os.listdir()” Method in Python?

Alternative Methods to List All Files and Directories in Python
Conclusion

What is the “os.listdir()” Method in Python?

The “os.listdir()” method of the “os” module is utilized to retrieve the list of all files and directories of the particular path. If you don’t indicate the path, the “os.listdir()” method retrieves all files and directories of the current/present working directory.

Syntax

os.listdir(path)

 
Parameters

Here in the syntax, the “path” parameter indicates an absolute or complete path representing the path-like object.

Return Value

The “os.listdir()” method retrieves the list containing all the files and directories of the specified path.

Note: The below snippet shows the files and directories that we need to list using the “os.listdir()” method.


Example 1: Listing All Files and Directories

In this example, we first imported the “os” module. Next, the “os.listdir()” method takes the specified path as an argument and retrieves all the files and directories. The files and directories are retrieved in the form of a list.

import os
dir1 = os.listdir(r'C:\Users\p\Documents\program')
print("Files and directories:\n")
print(dir1)

 
The retrieved list contains the files and directories:


Example 2: Listing All Files and Directories of Current Working Directory

In the below code, we get the path of the current working directory using the “os.getcwd()” method. After that, we pass the current working directory path to the “os.listdir()” method. This method retrieves the list containing the files and directories of the current working directory:

import os
path = os.getcwd()
dir1 = os.listdir(path)
print("Files and directories:\n")
print(dir1)

 
The following list displays the files and directories:


Without Path Parameter

We get the same result if we use the “os.listdir()” method without any argument/parameter to the path parameter value. Take this code as an example:

import os
dir1 = os.listdir()
print("Files and directories:\n")
print(dir1)

 
The below list shows the files and directories:


Example 3: Listing All Files and Directories Using a Loop

We can also list all the files and directories using a loop in Python. In the code below, the “os” module is imported and the complete path is assigned to the “path” variable. Next, the for loop is utilized to loop/iterate through the list containing the files and directory list. The “os.path.join()” method joins all the file paths and checks if the object is a file or directory using the “os.path.isfile()” and “os.path.isdir()” methods.

import os
path = r"C:\Users\p\Documents\program"

for i in os.listdir(path):
    path1 = os.path.join(path, i)
   
    if os.path.isfile(path1):
        print("File: ", i)
       
    elif os.path.isdir(path1):
        print("Directory: ", i)

 
The below snippet retrieves the file and directory:


Example 4: Listing Only Files Using List Comprehension

We can also list only the files using list comprehension. In the list comprehension, the “for loop” is utilized along with the “os.listdir()” method, and the “os.path.join()” method to retrieve only the list of the specified path. Here is an example code:

import os
dir1 = r'C:\Users\p\Documents\program'
file1 = [f for f in os.listdir(dir1) if os.path.isfile(os.path.join(dir1, f))]
print(file1)

 
The above code retrieves only the list value:


Example 5: Listing Only Directories Using List Comprehension

In a similar way to the previous example, we can list only the directories of the specified path. The “os.path.isdir()” method is used along with the other methods to retrieve only the directories of the given path.

import os
dir1 = r'C:\Users\p\Documents\program'
output = [f for f in os.listdir(dir1) if os.path.isdir(os.path.join(dir1, f))]
print(output)

 
The below output shows the list containing the directory only:

Alternative Methods to List All Files and Directories in Python

Multiple methods are employed to display all the files and directories in Python such as os.walk(), os.scandir(), and glob module. Let’s discuss each of these methods one by one:

Listing All Files Using “os.walk()” Method

The os.walk()” method can also retrieve the list containing all the files of the particular path. Here, in this example code, we imported the “os” module and provided the complete path to the variable named “dir1”. After that, the “for loop” iterates over the “os.walk()” method and retrieves the directory, directory name, and file name. Lastly, the “extend()” method adds the file to the empty list.

import os
dir1 = r'C:\Users\p\Documents\program'
list1 = []
for (dir1, dir_names, file1) in os.walk(dir1):
    list1.extend(file1)
print(list1)

 
The below snippet shows the files of the specified directory:


Listing All Files Using “os.scandir()” Method

The “os.scandir()” method can also list all the files in Python. The “os.scandir()” method retrieves the directory element along with the file information. Here in the below code, the for loop iterates over the directory entries and gets all the files of the specified path.

import os
dir1 = r'C:\Users\p\Documents\program'
for path in os.scandir(dir1):
    if path.is_file():
        print(path.name)

 
The below snippet shows all the files of the given path:


Listing All Files Using the “glob” Module

We can also use the “glob” module in Python to list all the files placed on a particular path. Here, in this code, we import the “glob” module and utilize the “glob.glob()” method to retrieve the list containing all the files.

import glob

dir1 = r'C:\Users\p\Documents\program\*.*'
print(glob.glob(dir1))

 
The below snippet shows the list containing all the files:


Listing All Files Using the “pathlib” Module

The “pathlib” module is used to deal with the file object in Python. The “pathlib” module can also be used to list all the files in Python. In the below code, the “pathlib” module is imported, and the “pathlib.path()” method is used to create the path object. Next, the for loop iterates over the return value of the “iterdir()” method. The “is_file()” method is utilized to verify/check whether the directory contains the file. If the file is found it is appended to the “list” and retrieved to the output.

import pathlib
dir1 = r'C:\Users\p\Documents\program'
list1 = []
d = pathlib.Path(dir1)
for i in d.iterdir():
    if i.is_file():
        list1.append(i)
print(list1)

 
The following code retrieves the list of specified paths:

Conclusion

The “os.listdir()” method retrieves a list of files and directories in a particular directory. If no directory is given, it returns to the current working directory. We can use this method to list all the files/directories in the current/present working directory. The for loop can also iterate over the files object to retrieve multiple files and directories. This post delivered a complete guide on Python os listdir via multiple examples.

About the author

Haroon Javed

Hi, I'm Haroon. I am an electronics engineer and a technical content writer. I am a tech geek who loves to help people to the best of my knowledge.