Checking file extension


I'm working on a certain program and I need to have it do different things if the file in question is a flac file, or an mp3 file. Could I just use this?

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

I'm not sure whether it will work.

EDIT: When I use that, it tells me invalid syntax. So what do I do?

5/5/2011 3:53:52 PM

Accepted Answer

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'))

(Thanks to Wilhem Murdoch for the list of args to endswith)

9/17/2015 7:39:53 PM

os.path provides many functions for manipulating paths/filenames. (docs)

os.path.splitext takes a path and splits the file extension from the end of it.

import os

filepaths = ["/folder/soundfile.mp3", "folder1/folder/soundfile.flac"]

for fp in filepaths:
    # Split the extension from the path and normalise it to lowercase.
    ext = os.path.splitext(fp)[-1].lower()

    # Now we can simply use == to check for equality, no need for wildcards.
    if ext == ".mp3":
        print fp, "is an mp3!"
    elif ext == ".flac":
        print fp, "is a flac file!"
        print fp, "is an unknown file format."


/folder/soundfile.mp3 is an mp3!
folder1/folder/soundfile.flac is a flac file!

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow