问题
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