![](/img/trans.png)
[英]How to save these elements read from a .txt file into an array/matrix in python
[英]How can I save a matrix in a txt file and then open it again as a matrix in python?
我试过这个:
import numpy as np
import os
outdir= "directory"
a = np.array([[1,2,3],[1,2,3]])
os.chdir(outdir)
np.savetxt("Image.bin", a)
f = open("directory/Image.bin")
m = np.fromfile(f, dtype=np.uint16)
print len(m)
ma = np.array(np.reshape(m, (2,3)))
print ma
但它返回此错误消息:“新数组的总大小必须保持不变”
我试图改变dtype,但它不起作用
你应该使用np.loadtxt
: http : np.loadtxt
尝试:
import numpy as np
a = np.array([[1,2,3],[1,2,3]])
np.savetxt("Image.bin", a)
m = np.loadtxt("Image.bin")
m
现在包含在相同的阵列作为a
。
numpy
内置了用于保存和加载数组作为二进制文件的函数。
numpy.save('data.npy', data)
将创建该文件(如果你没有,它将附加npy),和
data = numpy.load('data.npy')
将从文件中加载它。 这比将它们保存为文本文件更快,更节省空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.