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

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

其他回答

从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文件。

假设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'

操作系统。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!
if (file.split(".")[1] == "mp3"):
    print "its mp3"
elif (file.split(".")[1] == "flac"):
    print "its flac"
else:
    print "not compat"