Python 获取文件不分上下

Python get file regardless of upper or lower

我正在尝试在我的程序中使用 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

我该如何解决?

fnmatch.translate 需要一个字符串作为参数,而不是 glob 返回的 list/iterator 文件名,因此类似于:

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))