Find all text files in a directory with extension .txt in Python

With Python, it is easy to find all the files in a directory having a specific extension such as .txt. In this tutorial, I will show you how to do it using Python

Using glob

import glob, os

for file in glob.glob("*.txt"):

Using os.listdir:

import os
for file in os.listdir("/my_folder"):
    if file.endswith(".txt"):
        print(os.path.join("/my_folder", file))

Using os.walk

import os
for root, dirs, files in os.walk("/my_folder"):
    for file in files:
        if file.endswith(".txt"):
             print(os.path.join(root, file))
Last modified October 4, 2020