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

如何从os.walk遍历的音频文件列表中获取单个指定文件?

获取特定音乐文件的实现方法

你可以根据使用场景选择以下两种方式实现需求:

方法一:遍历过程中直接匹配目标文件(高效)

这种方式会在遍历目录时实时检查文件名,找到目标后立即停止遍历,适合仅需查找单个文件的场景:

import os

# 指定目标文件名
target_file = "11 - Mac DeMarco - On the Level.flac"
# 待遍历的根目录
root_dir = "/media/archsohee/Music/"

for root, _, files in os.walk(root_dir):
    for file in files:
        # 先筛选音频格式,再匹配目标文件名(后缀筛选可选,因目标文件名已包含后缀)
        if file.endswith(('.flac', '.mp3')) and file == target_file:
            full_path = os.path.join(root, file)
            print(f"找到目标文件:{full_path}")
            # 找到第一个匹配项后直接终止程序,如需查找所有同名文件可删除此行
            exit()
# 遍历结束未找到文件的提示
print("未找到指定的目标文件")

方法二:先收集所有音频文件,再查找目标

如果需要保留所有符合条件的音频文件列表,后续再从中检索目标文件,可使用这种方式:

import os

target_file = "11 - Mac DeMarco - On the Level.flac"
root_dir = "/media/archsohee/Music/"

# 收集所有.flac和.mp3文件的完整路径
music_file_paths = []
for root, _, files in os.walk(root_dir):
    for file in files:
        if file.endswith(('.flac', '.mp3')):
            music_file_paths.append(os.path.join(root, file))

# 在收集到的列表中查找目标文件
for path in music_file_paths:
    if os.path.basename(path) == target_file:
        print(f"找到目标文件:{path}")
        # 找到第一个匹配项后终止循环,如需获取所有匹配项可删除此行
        break
else:
    print("未找到指定的目标文件")

注意事项

  • 若目录中存在多个同名目标文件,上述代码仅返回第一个匹配项;如需获取所有同名文件,移除代码中的exit()或break语句,改为收集所有匹配路径即可。
  • 使用os.path.join()拼接路径可避免因系统路径分隔符差异导致的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:35:45