This short script uses the os.listdir function (that belongs to the OS module) to search through a given path (“.”) for all files that endswith “.txt”.
When the for loop finds a match it adds it to the list “newlist” by using the append function.
Find all files that endswith .txt
import os
items = os.listdir(".")
newlist = []
for names in items:
if names.endswith(".txt"):
newlist.append(names)
print newlist
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.