1

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

asked Dec 13, 2014 at 2:45
1
  • Are the arrays in those files all of the same shape (2x2) or can they differ? Commented Dec 13, 2014 at 18:12

2 Answers 2

3

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
answered Dec 13, 2014 at 2:57

1 Comment

elyase, thank you, I have used your fix many times since you submitted. Sorry it took so long to let you know how helpful you were.
1

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.

answered Dec 13, 2014 at 16:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.