Home > database >  search for a file in python when I only know few words that are in file
search for a file in python when I only know few words that are in file

Time:07-14

Beginner at python. I'm trying to search for a file saved in folder. For eg. file name is "Tommee Profitt, Fleurie, Mellen Gi - In The End - Mellen Gi Remix.mp3" but the program only have "In The End - Mellen Gi Remix" these words. How to search for a file in such case.

I tried

def findfile(name, path):
for dirpath, dirname, filename in os.walk(path):
    if name in filename:
        return os.path.join(dirpath, name)
filepath = findfile("In The End - Mellen Gi Remix", "C://Users//PycharmProjects")

but getting None as result.

CodePudding user response:

The problem is that os.walk() does not return what you're expecting it to. In your example, filename is actually a list of file names on each iteration, dirname is a list of directory names, and dirpath is the path those files and directories are in. Since you're not searching for directories, the middle value can be ignored. In Python, a single underscore _ is sometimes used as a "throwaway" variable name, that is a variable that must exist because of syntax, but whose value we don't actually care about.

def findfile(name, path):
    for dir, _, filenames in os.walk(path):
        for filename in filenames:
            if name in filename:
                return os.path.join(dir, filename)

Note that this can still fail to find a file in situations like if the CaSiNg doesn't match, or if áccénts don't match, or if a single character is off, etc.

  • Related