我试图在我的程序中使用this来获取mp3文件,无论如何,我都有这段代码:
import glob
import fnmatch, re
def custom_song(name):
for song in re.compile(fnmatch.translate(glob.glob("../music/*"+name+"*.mp3")), re.IGNORECASE):
print (song)
custom_song("hello")
但是当我执行脚本时,我收到以下错误:
File "music.py", line 4, in custom_song
for song in re.compile(fnmatch.translate(glob.glob("../music/*"+name+"*.mp3")), re.IGNORECASE):
TypeError: '_sre.SRE_Pattern' object is not iterable
我该如何解决?
答案 0 :(得分:0)
fnmatch.translate
期望一个字符串作为参数,而不是glob返回的文件名的列表/迭代器,因此类似于:
pattern = re.compile(fnmatch.translate(name + "*.mp3"),
re.IGNORECASE)
此外,您必须遍历某些文件名并查看它们是否match
已编译的模式:
directory = '../music/'
for name in os.listdir(directory):
if pattern.match(name):
print(os.path.join(directory, name))