遍历父目录子目录中的.wav文件



大家干杯,

我需要 python 3.6 中某些东西的帮助。所以我有这样的数据结构:

|main directory
|    |subdirectory's(plural)
|    |      |.wav files

我目前正在放置主目录的目录中工作,因此在此之前我不需要指定路径。所以首先我想遍历我的主目录并找到所有子目录。然后在它们中的每一个中,我想找到.wav文件,当完成处理它们时,我想转到下一个子目录,依此类推,直到所有子目录都打开,并处理所有.wav文件。我想对这些.wav文件所做的正是将它们输入到我的程序中,处理它们,以便我可以将它们转换为 numpy 数组,然后将该 numpy 数组转换为其他对象(确切地说是使用张量流,并希望转换为 TF 对象(。我写了整个过程,如果有人也有任何快速的建议,为什么不呢。 我尝试使用诸如以下的 for 循环来执行此操作:

for subdirectorys in open(data_path, "r"):
for files in subdirectorys:
#doing some processing stuff with the file 

问题是它总是引发错误 13,权限被拒绝显示在我给他的那data_path上,但当我去那里的房产时,它似乎还可以,所有权限都很好。 我尝试了一些其他方法,例如使用os.open或将循环替换为:

with open(data_path, "r") as data:

并且它总是引发权限被拒绝错误。 os.walk以某种方式工作,但这不是我需要的,当我尝试修改它时,id没有给出错误,但它也没有做任何事情。 只是说我不是 python 的任何专业程序员,所以我可能会错过一件明显的事情,但呃,我是来问和学习的。我也看到了很多类似的问题,但它们主要集中在.txt文件上,而不是专门针对我的情况,所以我需要在这里问它。 无论如何,提前感谢您的帮助。

编辑:如果你想要一个glob的例子(更理智(,这里是:

from pathlib import Path
# The pattern "**" means all subdirectories recursively,
# with "*.wav" meaning all files with any name ending in ".wav".
for file in Path(data_path).glob("**/*.wav"):
if not file.is_file():  # Skip directories
continue
with open(file, "w") as f:
# do stuff

有关详细信息,请参阅文档中的Path.glob()。球形模式是一件有用的事情。

以前的答案:

尝试使用 glob 或os.walk()。这是os.walk()的示例。

from os import walk, path
# Recursively walk the directory data_path
for root, _, files in walk(data_path):
# files is a list of files in the current root, so iterate them
for file in files:
# Skip the file if it is not *.wav
if not file.endswith(".wav"):
continue
# os.path.join() will create the path for the file
file = path.join(root, files)
# Do what you need with the file
# You can also use block context to open the files like this
with open(file, "w") as f:  # "w" means permission to write. If reading, use "r"
# Do stuff

请注意,您可能会对open()的作用感到困惑。它会打开一个文件进行读取、写入和追加。目录不是文件,因此无法打开。

我建议您在Google上搜索文档,并阅读更多有关所用功能的信息。该文档将比我提供更多帮助。

另一个更详细解释的好答案可以在这里看到。

import glob
import os
main = '/main_wavs'
wavs = [w for w in glob.glob(os.path.join(main, '*/*.wav')) if os.path.isfile(w)]

在路径 A/B/C 上的权限方面...A、B 和 C 都必须是可访问的。 对于文件,这意味着读取权限。 对于目录,它意味着读取和执行权限(列出内容(。

最新更新