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

时间:2014-12-26 16:38:00

标签: python io scipy wav

我想在主目录的子目录中使用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)

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

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'

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

2 个答案:

答案 0 :(得分:1)

只需在for循环中添加os.chdir(root)

for f in files:
    os.chdir(root)  # move to the directory where files are present
    s_rate, x  =  scipy.io.wavfile.read(f)
    rate.append(s_rate)
    data.append(x)

另一种方法是使用os.psth.join()将文件名与其路径连接为:

for f in files:
    s_rate, x  =  scipy.io.wavfile.read(os.path.join(root,f))  # join path with filename
    rate.append(s_rate)
    data.append(x)

答案 1 :(得分:1)

您需要使用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)