Get a filtered list of files in a directory

mhost picture mhost · Feb 9, 2010 · Viewed 371.4k times · Source

I am trying to get a list of files in a directory using Python, but I do not want a list of ALL the files.

What I essentially want is the ability to do something like the following but using Python and not executing ls.

ls 145592*.jpg

If there is no built-in method for this, I am currently thinking of writing a for loop to iterate through the results of an os.listdir() and to append all the matching files to a new list.

However, there are a lot of files in that directory and therefore I am hoping there is a more efficient method (or a built-in method).

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Feb 9, 2010
import glob

jpgFilenamesList = glob.glob('145592*.jpg')

See glob in python documenttion