python - 如何同时从多个子目录加载文件(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
解决方案
您可以使用本机 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
推荐阅读
- typescript - 如何声明 boolean 或 () => boolean 类型的属性
- python-3.x - wxPython 对象没有属性
- laravel - 如何在 Laravel 的三元运算符中使用 HREF
- c# - asp net core如何使用公共交通将数据从http get请求发布到Rabbit MQ?
- ios - Flutter 项目中“处理 Podfile 的安装后挂钩时发生错误”
- http - WinHttp.WinHttpRequest:服务器返回无效或无法识别的响应
- ruby-on-rails - Capybara/Selenium/Chrome:仅在调用 save_screenshot 时测试通过
- c# - 使用 await 的方法的连续性
- regex - 匹配除特定短语之外的所有内容
- c# - C# Foreach 对于 webbrowser 控件来说太快了