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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With