Answers:
假设m
是一个字符串,可以使用endswith
:
if m.endswith('.mp3'):
...
elif m.endswith('.flac'):
...
要不区分大小写并消除可能很大的else-if链:
m.lower().endswith(('.png', '.jpg', '.jpeg'))
.split('.')[-1]
?还是rpartition确实效率很高?
os.path
提供了许多用于处理路径/文件名的功能。(docs)
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是mp3! folder1 / folder / soundfile.flac是一个flac文件!
/.mp3
不被视为mp3文件。但是,这是应对领导空间的方式。例如,.gitignore
它不是文件格式
旧线程,但可能会帮助将来的读者...
如果没有其他原因,我会避免在文件名上使用.lower(),除了使您的代码与平台更独立外。(Linux的是情况下sensistive,.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
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"
.
s的文件,例如some.test.file.mp3
#!/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')