Python - Get list of File
Python - Get the list of all files in a directory and its sub-directories recursively
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.
Examples
1. Get the list of all files in given directory recursively
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
2. Get the list of all files with a specific extension in given directory
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.