Python OS.listdir and endswith( )

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

 

Leave a Reply

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