Skip to main content
 首页 » 编程设计

python之读取所有子目录中的 wav 文件

2024年10月25日8bluestorm

我想在我的主目录的子目录中使用 scipy.io.wavfile 模块读取所有的 wav 文件。

r_dir='/home/deepthought/Music/genres/' 
import os 
import scipy.io.wavfile 
data = [] 
rate = [] 
for root,sub,files in os.walk(r_dir): 
    files = sorted(files) 
    for f in files: 
        s_rate, x  =  scipy.io.wavfile.read(f) 
        rate.append(s_rate) 
        data.append(x) 

可以理解,这段代码不起作用,因为"file"只有文件名。这就是我收到错误的原因-

Traceback (most recent call last): 
File "<stdin>", line 4, in <module> 
File "/usr/lib/python2.7/dist-packages/scipy/io/wavfile.py", line 151, in read 
fid = open(filename, 'rb') 
IOError: [Errno 2] No such file or directory: 'hiphop.00000.au.wav' 

如何获取每个文件的完整路径??

请您参考如下方法:

您需要加入 root 和 f 才能使用 os.path.join 获取正确的文件路径:

for root, sub, files in os.walk(r_dir): 
    files = sorted(files) 
    for f in files: 
        s_rate, x  =  scipy.io.wavfile.read(os.path.join(root, f))  # <--- 
        rate.append(s_rate) 
        data.append(x)