简体   繁体   中英

how to store and read 4d numpy array

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

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM