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

时间:2019-05-16 09:57:39

标签: python numpy numpy-ndarray

我是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()最多接受1个参数(给定3个参数)

但我不知道如何解决

谢谢, M

1 个答案:

答案 0 :(得分:0)

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