Python获取文件,而不管大小上限 [英] Python get file regardless of upper or lower

查看:80
本文介绍了Python获取文件,而不管大小上限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在程序上使用 this mp3文件,无论大小写,我都有以下代码:

I'm trying to use this on my program to get an mp3 file regardless of case, and I've this code:

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

但是当我执行脚本时,出现以下错误:

But when I execute the script i get the following error:

 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返回的文件名列表/迭代器,因此像:

fnmatch.translate expects a string as an argument, not a list/iterator of filenames as would be returned by glob, thus something like:

pattern = re.compile(fnmatch.translate(name + "*.mp3"), 
    re.IGNORECASE)

此外,您必须遍历一些文件名,并查看它们是否与已编译的模式匹配:

Also, you must iterate over some filenames and see if they match the compiled pattern:

directory = '../music/'
for name in os.listdir(directory):
    if pattern.match(name):
        print(os.path.join(directory, name))

这篇关于Python获取文件,而不管大小上限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆