How to Get List of all Files in Directory and Sub-directories?

Python – Get List of all Files in a Directory and Sub-directories

To get the list of all files in a folder/directory and its sub-folders/sub-directories, we will use os.walk() function. The os.walk() function yields an iterator over the current directory, its sub-folders, and files.

In this tutorial, we shall go through some of the examples, that demonstrate how to get the list of all files in a directory and its sub-directories.

Example 1: Get the list of all files

In this example, we will take a path of a directory and try to list all the files in the directory and its sub-directories recursively.

Python Program

import os

path ="C:/workspace/python"
#we shall store all the file names in this list
filelist = []

for root, dirs, files in os.walk(path):
	for file in files:
        #append the file name to the list
		filelist.append(os.path.join(root,file))

#print all the file names
for name in filelist:
    print(name)

We have used nested Python For Loop in the above program.

Output

C:\pythonexamples\python-create-directory.png
C:\pythonexamples\python-remove-file.png
C:\pythonexamples\scatter-plot-example.py
C:\pythonexamples\tkinter-example.py
C:\pythonexamples\sample\example.py
C:\pythonexamples\sample\example1.py

Example 2: Get the list of all files with a specific extension

In this example, we will take a path of a directory and try to list all the files, with a specific extension .py here, in the directory and its sub-directories recursively.

Python Program

import os

path ="C:\workspace\python"

for root, dirs, files in os.walk(path):
	for file in files:
		if(file.endswith(".py")):
			print(os.path.join(root,file))

Output

C:\pythonexamples\scatter-plot-example.py
C:\pythonexamples\tkinter-example.py
C:\pythonexamples\sample\example.py
C:\pythonexamples\sample\example1.py

Summary

In this tutorial of Python Examples, we learned how to get the list of all files in a directory and its sub-directories.