我正在做一个特定的程序,我需要根据文件的扩展名做不同的事情。我能用这个吗?
if m == *.mp3
...
elif m == *.flac
...
发布于 2011-05-05 22:37:47
假设m
是一个字符串,您可以使用endswith
if m.endswith('.mp3'):
...
elif m.endswith('.flac'):
...
不区分大小写,并消除潜在的较大的else-if链:
m.lower().endswith(('.png', '.jpg', '.jpeg'))
发布于 2018-06-11 13:31:39
从Python3.4开始使用pathlib
。
from pathlib import Path
Path('my_file.mp3').suffix == '.mp3'
发布于 2011-05-05 23:03:35
看看模块fnmatch。它会做你想做的事。
import fnmatch
import os
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.txt'):
print file
https://stackoverflow.com/questions/5899497
复制相似问题