How to read only wav files in a directory using Py

2019-02-25 17:06发布

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?

2条回答
冷血范
2楼-- · 2019-02-25 17:32

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")]
查看更多
冷血范
3楼-- · 2019-02-25 17:36

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))
查看更多
登录 后发表回答