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

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

当前回答

操作系统。Path提供了许多操作路径/文件名的函数。(文档)

Os.path.splitext接受一个路径,并将文件扩展名从路径的末尾分离出来。

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."

给:

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

其他回答

操作系统。Path提供了许多操作路径/文件名的函数。(文档)

Os.path.splitext接受一个路径,并将文件扩展名从路径的末尾分离出来。

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."

给:

/folder/soundfile.mp3 is an mp3!
folder1/folder/soundfile.flac is a flac file!
file='test.xlsx'
if file.endswith('.csv'):
    print('file is CSV')
elif file.endswith('.xlsx'):
    print('file is excel')
else:
    print('none of them')

或者:

from glob import glob
...
for files in glob('path/*.mp3'): 
  do something
for files in glob('path/*.flac'): 
  do something else
import os
source = ['test_sound.flac','ts.mp3']

for files in source:
   fileName,fileExtension = os.path.splitext(files)
   print fileExtension   # Print File Extensions
   print fileName   # It print file name

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

如果没有其他原因,我将避免在文件名上使用.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