首页 > 解决方案 > 如何同时从多个子目录加载文件(jupyter)?

问题描述

我们是数据科学专业的学生。我们希望对 10 个不同子目录中的所有 .wav 文件应用多项功能。

我们可以使用以下代码在一个子目录上成功循环:

zcr = []

for f in sorted(os.listdir('/content/Data/genres_original/blues/')):
    if f.endswith('.wav'):
        # Load file and compute the requested features
        x, signal = librosa.load('/content/Data/genres_original/blues/' + f)
        zcr_ = librosa.feature.zero_crossing_rate(x)
        zcr.append(zcr_)

但我们未能在所有子目录中同时执行此操作。

我们如何同时循环所有子目录?

我们的文件夹结构:

 - Root folder

   - Folder 1
     - file 1
     - file 2
     - etc

   - Folder 2
     - file 1
     - file 2
     - etc

   - Folder 3
     - file 1
     - file 2
     - etc

   - Folder n
     - file 1
     - file 2
     - etc

标签: pythonloopsjupyterwavlibrosa

解决方案


您可以使用本机 os.walk() 方法以递归方式遍历您的目录:https ://www.tutorialspoint.com/python/os_walk.htm

你会得到类似的东西:

for root, dirs, files in os.walk(my_root_directory):
    for f in files:
        if os.path.splitext(f)[1] != '.wav':
            continue
        file_path = os.path.join(root, f)
        # do your stuff

我还向您推荐的替代方案是 path.py 库,它在与文件交互时非常方便:https ://path.readthedocs.io/en/latest/api.html


推荐阅读