简体   繁体   English

如何使用Python读取目录中的wav文件?

[英]How to read only wav files in a directory using Python?

from scipy.io.wavfile import read
files = [f for f in os.listdir('.') if os.path.isfile(f)]
print files
for i in range(0,1):
w = read(files[i])
print w

I need to read only .wav files from python working directory. 我只需要从python工作目录中读取.wav文件。 And store the each .wav files as a numpy array. 并将每个.wav文件存储为numpy数组。 This is my code. 这是我的代码。 But in this code all files are read. 但是在这段代码中,所有文件都被读取。 I only read the wav files in the directory? 我只读取目录中的wav文件吗? How it possible? 怎么可能?

Use the glob module and pass to it a pattern (like *.wav or whatever the files are named). 使用glob模块并向其传递一个模式(例如*.wav或任何命名的文件)。 It will return a list of files that match the criteria or the pattern. 它将返回符合条件或模式的文件列表。

import glob
from scipy.io.wavfile import read

wavs = []
for filename in glob.glob('*.wav'):
    print(filename)
    wavs.append(read(filename))

如果您不想使用glob ,那么类似的方法也将起作用:

files = [f for f in os.listdir('.') if os.path.isfile(f) and f.endswith(".wav")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM