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

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

当前回答

#!/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'

其他回答

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
if (file.split(".")[1] == "mp3"):
    print "its mp3"
elif (file.split(".")[1] == "flac"):
    print "its flac"
else:
    print "not compat"
#!/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'

我很惊讶没有一个答案建议使用pathlib库。

当然,它的使用是视情况而定的,但当涉及到文件处理或统计pathlib是黄金。

下面是一个片段:


import pathlib


def get_parts(p: str or pathlib.Path) -> None:
    p_ = pathlib.Path(p).expanduser().resolve()
    print(p_)
    print(f"file name: {p_.name}")
    print(f"file extension: {p_.suffix}")
    print(f"file extensions: {p_.suffixes}\n")


if __name__ == '__main__':
    file_path = 'conf/conf.yml'
    arch_file_path = 'export/lib.tar.gz'

    get_parts(p=file_path)
    get_parts(p=arch_file_path)

输出:

/Users/hamster/temp/src/pro1/conf/conf.yml
file name: conf.yml
file extension: .yml
file extensions: ['.yml']

/Users/hamster/temp/src/pro1/conf/lib.tar.gz
file name: lib.tar.gz
file extension: .gz
file extensions: ['.tar', '.gz']

操作系统。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!