walkergt
walkergt

Reputation: 45

Loading multiple files and saving them as variables

I need to load data from different files and save it as arrays. I have multple files named file.n.project.dat where n is 1-100. So far, it seems that using numpy is the best way to start. Each file is a 5 by 5 array. I need to be able to add/multiply arrays later on in my code.

Right now I have this code to load the data but how do I make each file it's own variable?

import numpy as np
for i in range(1,101):
    np.loadtxt('file.' + str(i) + '.project.dat')

So what i need to do is load multiple files AND create a variable for each file.

I have seen previous posts using vars() to create the variables but I am unable to make that work for my problem.

Upvotes: 2

Views: 1380

Answers (3)

Igor Yudin
Igor Yudin

Reputation: 403

You could use a dictionary.

d = {}
for i in range(1, 101):
    d['matrix{}'.format(i)] = np.loadtxt('file.{}.project.dat'.format(i))

That does not create new varialbles, but could possibly solve your task, as you can refer to matrices by names, d['matrix10']

Upvotes: 1

JAugust
JAugust

Reputation: 557

Can you try appending each of the values to a list and then try to access the list elements as one by one to get values. import numpy as np l = [] for i in range(1,101): l.append(np.loadtxt('file.' + str(i) + '.project.dat')) print l

I believe your problem should be solved this way. l will have all the values that you want.

Upvotes: 3

Daniel Jonsson
Daniel Jonsson

Reputation: 3893

Rather than creating a new variable for each array you want to load from disk, store them all in a collection such as a list or dictionary.

For instance:

import numpy as np

# As a list
my_arrays = [np.loadtxt('file.{}.project.dat'.format(i)) for i in range(1, 101)]

# As a dictionary
my_arrays = {i: np.loadtxt('file.{}.project.dat'.format(i)) for i in range(1, 101)}

Upvotes: 1

Related Questions