Site icon Machine Learning Projects

Python Program to Find All Files with .txt Extension Present Inside a Directory – 2023

Machine Learning Projects

Hey guys, in this blog we will see a Python Program to Find All Files with .txt Extension Present Inside a Directory.

Example 1: Using glob

import glob, os

os.chdir("my_dir")

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

Output

file3.txt
file2.txt
file1.txt

Example 2: Using os.listdir()

import os

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

Output

file1.txt
file2.txt
file3.txt

Example 3: 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

file3.txt
file2.txt
file1.txt

Check out our other python programming examples

Exit mobile version