You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何高效查找设备中所有.mp3文件?解决os.walk慢、glob局限问题

查找设备中所有.mp3文件的高效方案

以下几种方法比你试过的os.walk()和基础glob()更高效,耗时和资源占用更低:

1. 带递归参数的glob(Python 3.5+)

你可能不知道glob支持递归扫描,只需开启recursive=True参数,它的底层实现比手动写os.walk更优化,能直接递归遍历所有子目录并匹配.mp3文件:

import glob

# 替换为你要扫描的根路径,比如'/'(Linux/macOS)或'C:\\'(Windows)
mp3_files = glob.glob('/your/root/path/**/*.mp3', recursive=True)

这个方法语法简洁,且性能优于os.walk,因为它在匹配文件时减少了不必要的目录遍历判断。

2. 用os.scandir()手动实现递归扫描

os.scandir()是Python 3.5引入的,比os.listdir()更快,因为它返回的DirEntry对象缓存了文件的元数据(比如是否为目录、文件后缀),无需额外调用系统API获取,能大幅提升扫描速度。你可以基于它自己实现递归逻辑,提前过滤非.mp3文件和无需遍历的目录:

import os

def find_mp3_files(root_path):
    mp3_files = []
    for entry in os.scandir(root_path):
        if entry.is_file(follow_symlinks=False) and entry.name.endswith('.mp3'):
            mp3_files.append(entry.path)
        elif entry.is_dir(follow_symlinks=False):
            # 递归遍历子目录
            mp3_files.extend(find_mp3_files(entry.path))
    return mp3_files

# 调用方法
mp3_list = find_mp3_files('/your/root/path')

这种方式可以灵活跳过不需要的目录(比如系统缓存目录),进一步减少扫描时间。

3. 调用系统原生命令(最快方案)

系统自带的文件查找工具(如Linux的find、Windows的dir)是经过深度优化的原生程序,性能远优于Python实现的遍历逻辑。你可以用subprocess模块调用这些命令,直接获取结果:

Linux/macOS:

import subprocess

result = subprocess.run(['find', '/your/root/path', '-name', '*.mp3', '-type', 'f'], 
                       capture_output=True, text=True)
mp3_files = result.stdout.strip().split('\n')

Windows:

import subprocess

result = subprocess.run(['dir', '/s', '/b', r'C:\your\root\path\*.mp3'], 
                       capture_output=True, text=True, shell=True)
mp3_files = result.stdout.strip().split('\n')

这个方法是最快的,因为原生命令直接操作文件系统,没有Python层的额外开销,适合扫描超大范围的文件系统。

内容的提问来源于stack exchange,提问作者Sulav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 03:45:42