Search code examples
python-3.xwindowsmp3

Search .mp3 on computer using Python 3


I'm trying to search for all the files with an extension .mp3 in a computer using python 3.x.x i.e. searching through all drives, folders, and subfolders to make a list with all the file name in that list with their path.

music_list = ['c:\Users\username\Downlodes\music1.mp3',
              'c:\Users\username\Downlodes\music2.mp3',
              'c:\Users\username\Downlodes\music3.mp3',
              'd:\Folder1\username\oldDownlodes\music4.mp3'
              'e:\music folder\music5.mp3']

Please can anyone give me some code to do this function. I'm using Windows 8


Solution

  • You can use this code to check all the subfolders on a directory:

    subfolders = [f.path for f in os.scandir(folder) if f.is_dir() ]
    

    Then you can use this function to retrieve all the files with mp3 extension.

    import os, 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
    
    find('*.txt', '/path/to/dir')