Search code examples
pythonpython-2.7globuppercaselowercase

Python get file regardless of upper or lower


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

How can I fix it?


Solution

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