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

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

Table of Contents

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

  • Here we have used the glob() python package to get all the ‘.txt’ files.
  • We have used glob.glob(“*.txt”) to get a list of all “.txt” files.

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

  • Here we have used the os python package and a special string function endswith() to get all the ‘.txt’ files.

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

  • It is also similar to the above method except for the fact here we are using os.walk() method.
  • It generates the file names in a directory tree by walking the tree either top-down or bottom-up. 

Check out our other python programming examples

Leave a Reply

Your email address will not be published. Required fields are marked *