Join our newsletter for the latest updates.

Python Program to Find All File with .txt Extension Present Inside a Directory

In this example, you will learn to find all files with .txt extension present inside a directory.

To understand this example, you should have the knowledge of the following Python programming topics:


Example 1: Using glob

import glob, os

os.chdir("my_dir")

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

Output

c.txt
b.txt
a.txt

Example 2: Using os

import os

for file in os.listdir("my_dir"):
    if file.endswith(".txt"):
        print(file)

Output

a
{21: 'b', 14: 'c'}

pop() also returns the value of the key passed.


Using os.walk

import os

for root, dirs, files in os.walk("my_dir"):
    for file in files:
        if file.endswith(".txt"):
            print(file)

Output

c.txt
b.txt
a.txt