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

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

当前回答

或者:

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

其他回答

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

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

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

m.lower().endswith(('.png', '.jpg', '.jpeg'))
#!/usr/bin/python

import shutil, os

source = ['test_sound.flac','ts.mp3']

for files in source:
  fileName,fileExtension = os.path.splitext(files)

  if fileExtension==".flac" :
    print 'This file is flac file %s' %files
  elif  fileExtension==".mp3":
    print 'This file is mp3 file %s' %files
  else:
    print 'Format is not valid'
file='test.xlsx'
if file.endswith('.csv'):
    print('file is CSV')
elif file.endswith('.xlsx'):
    print('file is excel')
else:
    print('none of them')

如果你的文件上传了

import os


file= request.FILES['your_file_name']          #Your input file_name for your_file_name
ext = os.path.splitext(file.name)[-1].lower()


if ext=='.mp3':
    #do something

elif ext=='.xls' or '.xlsx' or '.csv':
    #do something

else:
    #The uploaded file is not the required format

从Python3.4开始使用。

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

如果您正在处理包含句点的文件夹,则可以使用

Path('your_folder.mp3').is_file() and Path('your_folder.mp3').suffix == '.mp3'

确保后缀为.mp3的文件夹不会被解释为mp3文件。