如何查看文件的扩展名?

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

if m == *.mp3
...
elif m == *.flac
...
447846 次浏览

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

os.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!
#!/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

一个简单的方法是:

import os


if os.path.splitext(file)[1] == ".mp3":
# do something

os.path.splitext(file)将返回一个有两个值的元组(没有扩展名的文件名+只有扩展名的文件名)。因此,第二个索引([1])只提供扩展名。最酷的是,如果需要的话,这样你也可以很容易地访问文件名!

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

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

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

为什么不使用再保险?(尽管为了更加健壮,您应该检查每个文件的神奇文件头… 如何在python中检查没有扩展名的文件类型?) < / p >
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

从Python3.4开始使用pathlib

from pathlib import Path
Path('my_file.mp3').suffix == '.mp3'
file='test.xlsx'
if file.endswith('.csv'):
print('file is CSV')
elif file.endswith('.xlsx'):
print('file is excel')
else:
print('none of them')

你应该确保“文件”;在检查扩展之前实际上不是一个文件夹。上面的一些答案没有说明带句点的文件夹名称。(folder.mp3是一个有效的文件夹名)。


检查文件扩展名:

import os


file_path = "C:/folder/file.mp3"
if os.path.isfile(file_path):
file_extension = os.path.splitext(file_path)[1]
if file_extension.lower() == ".mp3":
print("It's an mp3")
if file_extension.lower() == ".flac":
print("It's a flac")

输出:

It's an mp3

检查文件夹中所有文件的扩展名:

import os


directory = "C:/folder"
for file in os.listdir(directory):
file_path = os.path.join(directory, file)
if os.path.isfile(file_path):
file_extension = os.path.splitext(file_path)[1]
print(file, "ends in", file_extension)

输出:

abc.txt ends in .txt
file.mp3 ends in .mp3
song.flac ends in .flac

比较多种类型的文件扩展名:

import os


file_path = "C:/folder/file.mp3"
if os.path.isfile(file_path):
file_extension = os.path.splitext(file_path)[1]
if file_extension.lower() in {'.mp3', '.flac', '.ogg'}:
print("It's a music file")
elif file_extension.lower() in {'.jpg', '.jpeg', '.png'}:
print("It's an image file")

输出:

It's a music file

如果你的文件上传了

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

我很惊讶没有一个答案建议使用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']