Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use fnmatch.filter to filter files by more than one possible file extension

Given the following piece of python code:

for root, dirs, files in os.walk(directory):     for filename in fnmatch.filter(files, '*.png'):         pass 

How can I filter for more than one extension? In this special case I want to get all files ending with *.png, *.gif, *.jpg or *.jpeg.

For now I came up with

for root, dirs, files in os.walk(directory):     for extension in ['jpg', 'jpeg', 'gif', 'png']:         for filename in fnmatch.filter(files, '*.' + extension):             pass 

But I think it is not very elegant and performant.

Someone has a better idea?

like image 549
tyrondis Avatar asked Mar 18 '11 12:03

tyrondis


2 Answers

If you only need to check extensions (i.e. no further wildcards), why don't you simply use basic string operations?

for root, dirs, files in os.walk(directory):     for filename in files:         if filename.endswith(('.jpg', '.jpeg', '.gif', '.png')):             pass 
like image 145
eumiro Avatar answered Sep 25 '22 13:09

eumiro


I think your code is actually fine. If you want to touch every filename only once, define your own filtering function:

def is_image_file(filename, extensions=['.jpg', '.jpeg', '.gif', '.png']):     return any(filename.endswith(e) for e in extensions)  for root, dirs, files in os.walk(directory):     for filename in filter(is_image_file, files):         pass 
like image 30
Sven Marnach Avatar answered Sep 22 '22 13:09

Sven Marnach