Oct. 04, 2012

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"):
print newlist

Share this article

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.


Download Our Free Guide To Learning Python

* indicates required

Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.