Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check the extension of a file?

People also ask

How can I see the extension of a file?

Open File Explorer; if you do not have an icon for this in the task bar; click Start, click Windows System, and then File Explorer. Click the View tab in File Explorer. Click the box next to File name extensions to see file extensions.

How do I get the file extension to show in a folder?

Click Tools, and then click Folder Options. Scroll down and then click Folder and search options. Click the View tab. Scroll down until you notice Hide extensions for known file types, un-check this line by clicking the check box.


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!

Use pathlib From Python3.4 onwards.

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

Look at module fnmatch. That will do what you're trying to do.

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print file