How to find files with certain extension only in Python

We could use glob.glob module to find the files with certain extension only in Python.

import glob

targetPattern = r"C:\Test\*.txt"
glob.glob(targetPattern)

The above codes demonstrates how to find the files with extension txt in the directory C:\Test.

Find files with certain extension in the directory and its subdirectories

The pattern C:\Test\*.txt only finds the txt files in the directory C:\Test, but not in its subdirectories. If you want to also find txt files in the subdirectories, you could modify the pattern a bit.

import glob

targetPattern = r"C:\Test\**\*.txt"
glob.glob(targetPattern)

The wild cards ** between Test and .text means it should find the txt files both in the directory and its subdirectories.