【问题标题】:reading wav files in all subdirectories读取所有子目录中的 wav 文件
【发布时间】:2014-12-26 16:37:59
【问题描述】:

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

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

【问题讨论】:

    标签: python io scipy wav


    【解决方案1】:

    您需要将rootf 一起使用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)
    

    【讨论】:

      【解决方案2】:

      只需在 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) os.chdir(root) 可以不在循环中。 (在for循环之前)2)改变目录是有风险的,特别是如果根目录是相对路径,它会阻止os.walk递归正常工作。
      • 将另一个标记为正确,因为它看起来更通用。
      猜你喜欢
      • 2014-11-10
      • 2013-02-28
      • 2019-11-13
      • 2013-12-02
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多