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

半世苍凉 提交于 2019-12-02 05:00:35

问题


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. And store the each .wav files as a numpy array. This is my code. But in this code all files are read. I only read the wav files in the directory? How it possible?


回答1:


Use the glob module and pass to it a pattern (like *.wav or whatever the files are named). 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))



回答2:


If you don't want to use glob, then something like this will also work:

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


来源:https://stackoverflow.com/questions/18895919/how-to-read-only-wav-files-in-a-directory-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!