如何存储和读取 4d numpy 数组

how to store and read 4d numpy array

我是 Python 的新手。我正在尝试将一个 4d numpy 数组存储在一个文件中(完成)并读取该文件的值(这就是问题所在)。代码是:

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

我收到错误:

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)

但我不知道如何解决

谢谢, M

保存和读取 numpy 数组的最简单解决方案是仅使用 numpy 函数 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')