无论上层还是下层,Python都可以获取文件

时间:2015-04-30 16:45:15

标签: python python-2.7 glob uppercase lowercase

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

我该如何解决?

1 个答案:

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