我在一个特定的程序上工作,我需要根据文件的扩展名做不同的事情。我能用这个吗?
if m == *.mp3
...
elif m == *.flac
...
我在一个特定的程序上工作,我需要根据文件的扩展名做不同的事情。我能用这个吗?
if m == *.mp3
...
elif m == *.flac
...
当前回答
操作系统。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!
其他回答
查看模块fnmatch。它会达到你想要的效果。
import fnmatch
import os
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.txt'):
print file
假设m是一个字符串,你可以使用endswith:
if m.endswith('.mp3'):
...
elif m.endswith('.flac'):
...
不区分大小写,并消除可能较大的else-if链:
m.lower().endswith(('.png', '.jpg', '.jpeg'))
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
或者:
from glob import glob
...
for files in glob('path/*.mp3'):
do something
for files in glob('path/*.flac'):
do something else
操作系统。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!