Checking file extension

2019-01-06 09:16发布

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?

10条回答
我想做一个坏孩纸
2楼-- · 2019-01-06 09:46

or perhaps:

from glob import glob
...
for files in glob('path/*.mp3'): 
  do something
for files in glob('path/*.flac'): 
  do something else
查看更多
姐就是有狂的资本
3楼-- · 2019-01-06 09:47
if (file.split(".")[1] == "mp3"):
    print "its mp3"
elif (file.split(".")[1] == "flac"):
    print "its flac"
else:
    print "not compat"
查看更多
聊天终结者
4楼-- · 2019-01-06 09:49

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)

查看更多
Evening l夕情丶
5楼-- · 2019-01-06 09:51

An old thread, but may help future readers...

I would avoid using .lower() on filenames if for no other reason than to make your code more platform independent. (linux is case sensistive, .lower() on a filename will surely corrupt your logic eventually ...or worse, an important file!)

Why not use re? (Although to be even more robust, you should check the magic file header of each file... How to check type of files without extensions in python? )

import re

def checkext(fname):   
    if re.search('\.mp3$',fname,flags=re.IGNORECASE):
        return('mp3')
    if re.search('\.flac$',fname,flags=re.IGNORECASE):
        return('flac')
    return('skip')

flist = ['myfile.mp3', 'myfile.MP3','myfile.mP3','myfile.mp4','myfile.flack','myfile.FLAC',
     'myfile.Mov','myfile.fLaC']

for f in flist:
    print "{} ==> {}".format(f,checkext(f)) 

Output:

myfile.mp3 ==> mp3
myfile.MP3 ==> mp3
myfile.mP3 ==> mp3
myfile.mp4 ==> skip
myfile.flack ==> skip
myfile.FLAC ==> flac
myfile.Mov ==> skip
myfile.fLaC ==> flac
查看更多
登录 后发表回答