Home > Mobile >  what is the optimal way of finding alll the .mp3 files in a device?
what is the optimal way of finding alll the .mp3 files in a device?

Time:01-07

os.walk() method is easy but it takes lot of time to scan through all the files?

any method with less time and low processing power?

I've tried both os.walk() and glob() method but glob only returns files in the ame directory and os.walk() is too slow.

CodePudding user response:

you can try scandir

import os
import fnmatch

def find_mp3_files(root_dir):
    matches = []
    with os.scandir(root_dir) as entries:
        for entry in entries:
            if entry.is_file() and fnmatch.fnmatch(entry.name, '*.mp3'):
                matches.append(entry.path)
            elif entry.is_dir():
                matches.extend(find_mp3_files(entry.path))
    return matches

mp3_files = find_mp3_files('/path/to/root/directory')

CodePudding user response:

With glob() you can scan all system directories recursively. Here is how you can do it:

import glob

# Use glob to find all the mp3 files in the specified root directory and its subdirectories
root_dir = '/path/to/root/directory/'
mp3_files = glob.glob(root_dir   '**/*.mp3', recursive=True)

print(mp3_files)

For linux based Operating systems including MacOS, you can use

root_dir = '/'

For Windows OS

root_dir = 'C:/' 
# Replace C with other drive letters present on your system.
  • Related