Devi Prasad Khatua
Devi Prasad Khatua

Reputation: 1235

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

Upvotes: 5

Views: 4815

Answers (3)

acushner
acushner

Reputation: 9946

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

exts = tuple(extensions)
[f for f in filenames if f.endswith(exts)]

Upvotes: 10

Snild Dolkow
Snild Dolkow

Reputation: 6876

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.

Upvotes: 1

scytale
scytale

Reputation: 12641

you can use a list comprehension for a concise way to do this:

[f for f in filenames for e in extensions if f.endswith(e)]

Upvotes: 0

Related Questions