Take the 2-minute tour ×

Is it possible to get Python to look in a folder and put all of the filenames (with a certain extension) into a list?


[filename1.txt, filename2.txt,...]
share|improve this question
add comment

2 Answers

up vote 8 down vote accepted

You can do this easily with the glob module:

import glob
filenames = glob.glob('<some_path>/*.<extension>')
share|improve this answer
What's the "\" there for? –  DSM Sep 13 '12 at 1:48
good, use os.path.basename(x) for x in glob(...) if you don't want the full paths. –  wim Sep 13 '12 at 1:49
@DSM wim beat me to the edit. I should have put a "/" of course. –  Yuushi Sep 13 '12 at 1:51
Ah, okay. I thought maybe you were trying to escape the asterisk for a second (which I've sometimes done myself, accidentally.) –  DSM Sep 13 '12 at 1:52
add comment

Here's a quick answer I found.

import os

txt_files = filter(lambda x: x.endswith('.txt'), os.listdir('mydir'))
share|improve this answer
If you are going to do it that way you might as well use os.path.splitext() instead of endswith –  gnibbler Sep 13 '12 at 1:48
add comment

Your Answer


