Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : Check for filename ending with an extension present in a list of extensions

Basically I want the filenames ending with an extension present in the list of extensions. Here is my code in python. I have taken some sample filenames as a list as given below:

extensions = ['.mp3','.m4a','.wma']
filenames = ['foo1.mp3','foo2.txt','foo3.m4a','foo4.mp4']
for filename in filenames:
    for extension in extensions:
         if filename.endswith(extension):
             print filename
             break

This is working but I am curious to know whether there's a more efficient or short way of doing the same thing in python. Thank you

like image 834
Devi Prasad Khatua Avatar asked Feb 09 '23 02:02

Devi Prasad Khatua


2 Answers

endswith accepts a tuple, so it's very easy:

exts = tuple(extensions)
[f for f in filenames if f.endswith(exts)]
like image 171
acushner Avatar answered Feb 13 '23 22:02

acushner


print [f for f in filenames if f[f.rindex('.'):] in extensions]

How it works:

It's a list comprehension, so the interesting part is after the "if".

Well, we use f.rindex('.') to find the last dot in the filename. Then we use slicing to get the part of f from there to the end. And finally, "in extensions" simply checks if the extensions list contains the file's extension.

like image 41
Snild Dolkow Avatar answered Feb 13 '23 20:02

Snild Dolkow