Reputation: 1235
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
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
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
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