Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a filtered list of files in a directory

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).

like image 330
mhost Avatar asked Feb 08 '10 23:02

mhost


People also ask

How do I get a list of files in a directory in C++?

Call opendir() function to open all file in present directory. Initialize dr pointer as dr = opendir("."). If(dr) while ((en = readdir(dr)) != NULL) print all the file name using en->d_name.


2 Answers

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

See glob in python documenttion

like image 53
Ignacio Vazquez-Abrams Avatar answered Sep 19 '22 15:09

Ignacio Vazquez-Abrams


glob.glob() is definitely the way to do it (as per Ignacio). However, if you do need more complicated matching, you can do it with a list comprehension and re.match(), something like so:

files = [f for f in os.listdir('.') if re.match(r'[0-9]+.*\.jpg', f)] 

More flexible, but as you note, less efficient.

like image 21
Ben Hoyt Avatar answered Sep 21 '22 15:09

Ben Hoyt