Reputation: 129
from scipy.io.wavfile import read
filepath = glob.glob('*.wav') #list
rate,data = [read(fp) for fp in filepath]
and I get :
ValueError: too many values to unpack
but i can load only once a time.
like this:
rate,data = read('001.wav')
print rate
print data
and I get:
44100
[0 0 0 ..., 0 0 0]
How could I load the rate and data to two arrays, and if I do :
datas = [read(fp) for fp in filepath]
I will get :
[(44100, array([0, 0, 0, ..., 0, 0, 0], dtype=int16)), (44100, array([0, 0, 0, ..., 0, 0, 1], dtype=int16)), ..., (44100, array([0, 0, 0, ..., 0, 0, 0], dtype=int16))]
or there is any way I can split the datas to rate and data after loading.
Thanks.
Upvotes: 1
Views: 602
Reputation: 22341
You can split it after loading using the inverse zip function (as explained in this answer):
In [13]: rate, data = zip(*datas)
In [14]: rate
Out[14]: (44100, 44100)
In [15]: data
Out[15]: (array([0, 0, 0, 0, 0, 0]), array([0, 0, 0, 0, 1]))
I would say that this is an acceptable way to do it in this scenario, although I think using a more classical for loop, where you append to lists, without using list comprehension, would be cleaner:
rates = []
datas = []
for fp in filepath:
rate, data = read(fp)
rates.append(rate)
datas.append(data)
The reason you got a ValueError
in the first case is because you are unpacking a list of all tuples for each of your files (obviously more than 2 given the error message) into only two variables - rate and data.
Upvotes: 1
Reputation: 18541
You can use zip(*x)
to format them into one list of rates and one list of the data lists.
raw_data = [read(fp) for fp in filepath]
rates, data = zip(*raw_data)
For example,
raw_data = zip(range(10), range(20, 30))
# [(0, 20), (1, 21), (2, 22), (3, 23), (4, 24), (5, 25), (6, 26), (7, 27), (8, 28), (9, 29)]
zip(*raw_data)
# [(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (20, 21, 22, 23, 24, 25, 26, 27, 28, 29)]
Upvotes: 1