简体   繁体   English

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

[英]how to store and read 4d numpy array

I am new to Python. 我是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). 我试图将4d numpy数组存储在一个文件中(完成它)并读取该文件的值(存在问题)。 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) infile.read(mnew [i,j,k,0],mnew [i,j,k,1],mnew [i,j,k,2])TypeError:read()最多需要1个参数(给定3个) )

but I don't know how to fix it 但我不知道如何解决它

Thanks, M 谢谢,M

The easiest solution to save and read numpy arrays is to just use numpy functions np.save and np.load . 保存和读取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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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