Search code examples
windows-8searchmp3python-3.x

Efficient way to search for files in python 3


Hi I'm trying to search for all the .mp3 files on my computer and I have a code which takes the file type like .mp3, .txt, etc as one input and the folder path as other input and search through all the subfolder in the specified path and the folder itself for the file type and returns the path to the file in a list, this takes some time if the folder has so many subfolders or instead if I give a drive name as input for the 'path'. I need an efficient way to do this. If I search for all the subfolders in a folder first and then pass the subfolders path to the function will it work faster?

import os
import fnmatch


def find(pattern, path):
    result = []
    for root, dirs, files in os.walk(path):
        for name in files:
            if fnmatch.fnmatch(name, pattern):
                result.append(os.path.join(root, name))
    return result 

Solution

  • I think this is efficient enough... The command where.exe /R C:\ *.mp3 will do exectly the same as your python script. And your script is even faster then the built in windows command so it should be efficient enough. I don't know if this was your exact question, if it wasn't I think it isn't clear what you really mean.

    By the way you could use this code which will print the results in realtime:

    import os
    from fnmatch import fnmatch
    
    
    def find(pattern, path):
        for root, dirs, files in os.walk(path):
            for name in files:
                if fnmatch(name, pattern):
                    yield os.path.join(root, name)
    

    The difference is that if you for example do

    for i in find('*.mp3', 'C:\\'):
        print(i)
    

    it will print each result as fast as possible. Your script will return the whole list when the operation is complete, while this script will print directly.

    I don't know how to explain it better because my English isn't the best, but you could just try it and see the difference.

    It's still faster than the windows built in command by the way.