Pet*_*ter 17 python binary numpy
我想将numpy float数组的内容保存为原始二进制文件,作为带符号的16位整数.我尝试使用ndarray.tofile完成此操作,但我无法找出正确的格式字符串.似乎文件以双格式保存,不管我如何选择格式字符串.我该怎么做呢?谢谢.
Bi *_*ico 38
我认为最简单的方法是首先将数组转换为int16,
array.astype('int16').tofile(filename)
Run Code Online (Sandbox Code Playgroud)
看一下struct模块,试试这个例子:
import struct
import numpy
f=open("myfile","wb")
mydata=numpy.random.random(10)
print(mydata)
myfmt='f'*len(mydata)
# You can use 'd' for double and < or > to force endinness
bin=struct.pack(myfmt,*mydata)
print(bin)
f.write(bin)
f.close()
Run Code Online (Sandbox Code Playgroud)