写numpy的数组,其大小以二进制文件 [英] write numpy array with its size to binary file
问题描述
我需要一个二维数组numpy的写入文件,包括它的尺寸,所以我可以从C ++程序读取它,并创建相应的数组。
I need to write a 2D numpy array to a file, including its dimensions so I can read it from a C++ program and create the corresponding array.
我已经写了一些简单的code,节省阵列,它可以从C ++读取,但如果我尝试先写数组的大小,它总是给我一个错误。
I have written some simple code that saves the array and it can be read from C++, but if I try to write the array's size first it always gives me an error.
下面是我简单的python code:
Here's my simple python code:
1 file = open("V.bin","wb")
2 file.write(V.shape)
3 file.write(V)
4 file.close()
第二行给出了错误,我也试着:
The second line gives the error, I've also tried:
n1, n2 = V.shape
file.write(n1)
file.write(n2)
但它不工作的。
我添加了错误它显示:
回溯(最近通话最后一个):
file.write(V.shape [0])
类型错误:必须是字符串或缓冲区,不是int
Traceback (most recent call last): file.write(V.shape[0]) TypeError: must be string or buffer, not int
谢谢!
推荐答案
可以,如果你想将其保存为ASCII使用 numpy.savetext
。
You can use numpy.savetext
if you want to save it as ascii.
或者(因为它看起来像你使用二进制数据处理),如果要保存原始数据流,你可以使用 ndarray.tostring
来获得字节串,你可以转储到文件中直接。
Alternatively (since it looks like you're dealing with binary data), if you want to save the raw data stream, you could use ndarray.tostring
to get a string of bytes that you can dump to the file directly.
这种方法的好处是,你可以创建自己的文件格式。缺点是,你需要为它实际上写入到文件来创建一个字符串。
The advantage of this approach is that you can create your own file format. The downside is that you need to create a string in order to actually write it to the file.
既然你说你在第二行得到一个错误,这是一个错误,因为 f.write
需要一个字符串。你想传递一个元组
或 INT
秒。你可以使用 struct.pack
来解决这个问题:
And since you say that you're getting an error on the second line, it's an error because f.write
expects a string. You're trying to pass it a tuple
or int
s. You could use struct.pack
to solve this problem:
f.write(struct.pack('2i',*array.shape))
这篇关于写numpy的数组,其大小以二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!