0

I am new to Python. I am trying to store a 4d numpy array in a file (done it) and read the values of this file (there's the problem). The code is:

import numpy as np

Lx=6;Ly=6,Lz=2 
mat=np.zeros((Lx,Ly,Lz,3),dtype=np.float)

mat=np.random.rand(Lx,Ly,Lz,3)

outfile=open("config.txt","w")


for i in range(0,Lx):
    for j in range(0,Ly):
        for k in range(0,Lz):
           print(mat[i,j,k,0], mat[i,j,k,1], mat[i,j,k,2],file=outfile)

outfile.close() 


mnew=np.zeros((Lx,Ly,Lz,3),dtype=np.float)

infile=open("config.txt","r")

for i in range(0,Lx):
    for j in range(0,Ly):
        for k in range(0,Lz):
            infile.read(mnew[i,j,k,0], mnew[i,j,k,1], mnew[i,j,k,2])

I get the error:

infile.read(mnew[i,j,k,0], mnew[i,j,k,1], mnew[i,j,k,2]) TypeError: read() takes at most 1 argument (3 given)

but I don't know how to fix it

Thanks, M

3
  • Take a look at python's read function here Commented May 16, 2019 at 10:37
  • I don't see how this helps Commented May 16, 2019 at 11:03
  • Python's read function of files reads from files, but it does not read directly into variables. If you insist on using read like such without using proper numpy functions for loading and saving files, what I think you want is to read the lines using readlines and insert into variables Commented May 16, 2019 at 11:06

1 Answer 1

1

The easiest solution to save and read numpy arrays is to just use numpy functions np.save and np.load.

import numpy as np
example = np.random.rand(6, 6, 2, 3)

#save
example.save('example.npy')

#read back
example_copy = np.load('example.npy')
Sign up to request clarification or add additional context in comments.

4 Comments

this is a 4d matrix, not an array
@mgeo in numpy terms array means ndarray, which can have arbitrary dimension. mat and mnew are already ndarrays
thanks, I tried: with open('newstore','w') as ff: np.save(ff,mat) ff.closed mnew=np.load(ff) but it didn't work
You can even skip the open with these functions. I added a minimal example.

Your Answer

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.