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
endswith
accepts a tuple, so it's very easy:
exts = tuple(extensions)
[f for f in filenames if f.endswith(exts)]
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.
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