Reputation: 343
I would like to be able to create numpy arrays based on a number that could change.
For example, say I have 50 text files containing a 2x2 set of numbers
I would like to load those 50 files as numpy arrays and use them later in the code. A sample of code may look like:
import load numpy as np
num = 50 #this could change based on different conditions
for i in arange(num):
data%d % i = np.loadtxt("datafromafile%d.txt" % i)
Is this something like this possible? Thanks
Upvotes: 1
Views: 1589
Reputation: 239
As a oneliner it would be:
NUM = 50
data = [np.loadtxt("datafromafile%d.txt" % value) for value in np.arange(NUM)]
or
FILES = ['file1', 'file2', 'file3']
data = {key: np.loadtxt(key) for key in FILES}
as a dict with the filename as key.
Upvotes: 1
Reputation: 40963
You can store them in a list:
data = list()
for i in arange(num):
data.append(np.loadtxt("datafromafile%d.txt" % i))
Then you can access each array with:
>>> data[0] + data[1] # sum of the first and second numpy array
Upvotes: 3