python – How can I check the extension of a file?

python – How can I check the extension of a file?

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

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!
    else:
        print fp, is an unknown file format.

Gives:

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

python – How can I check the extension of a file?

Use pathlib From Python3.4 onwards.

from pathlib import Path
Path(my_file.mp3).suffix == .mp3

Leave a Reply

Your email address will not be published. Required fields are marked *