我在一个特定的程序上工作,我需要根据文件的扩展名做不同的事情。我能用这个吗?

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

当前回答

if (file.split(".")[1] == "mp3"):
    print "its mp3"
elif (file.split(".")[1] == "flac"):
    print "its flac"
else:
    print "not compat"

其他回答

一个老帖子,但可能对未来的读者有所帮助…

如果没有其他原因,我将避免在文件名上使用.lower(),只是为了使您的代码更独立于平台。(linux是区分大小写的,文件名上的.lower()最终肯定会破坏你的逻辑…或者更糟,一个重要的文件!)

为什么不用re?(尽管为了更加健壮,您应该检查每个文件的神奇文件头… 如何检查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)) 

输出:

myfile.mp3 ==> mp3
myfile.MP3 ==> mp3
myfile.mP3 ==> mp3
myfile.mp4 ==> skip
myfile.flack ==> skip
myfile.FLAC ==> flac
myfile.Mov ==> skip
myfile.fLaC ==> flac
file='test.xlsx'
if file.endswith('.csv'):
    print('file is CSV')
elif file.endswith('.xlsx'):
    print('file is excel')
else:
    print('none of them')

假设m是一个字符串,你可以使用endswith:

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

不区分大小写,并消除可能较大的else-if链:

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

或者:

from glob import glob
...
for files in glob('path/*.mp3'): 
  do something
for files in glob('path/*.flac'): 
  do something else

查看模块fnmatch。它会达到你想要的效果。

import fnmatch
import os

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