How can I check the extension of a file?

wkoomson picture wkoomson · May 5, 2011 · Viewed 280.7k times · Source

I'm working on a certain program where I need to do different things depending on the extension of the file. Could I just use this?

if m == *.mp3
   ...
elif m == *.flac
   ...

Answer

lafras picture lafras · May 5, 2011

Assuming m is a string, you can use endswith:

if m.endswith('.mp3'):
...
elif m.endswith('.flac'):
...

To be case-insensitive, and to eliminate a potentially large else-if chain:

m.lower().endswith(('.png', '.jpg', '.jpeg'))