我正在尝试将numpy数组写入文件,但是文件格式是这样的,每个值必须仅包含表示64位浮点数所需的8个字节。
尽我所知,具有array.dtype ='float64'的ndarray.tofile(array)无法完成此操作,那么如何快速执行此操作?
最佳答案
tofile
已经创建了您描述的二进制文件。您确定调用正确吗?如果要用代码打开文件,还记得以二进制模式打开文件吗?这是tofile
正常工作的示例:
>>> import numpy as np
>>> a = np.array([1, 2, 3], dtype='float64')
>>> a
array([ 1., 2., 3.])
>>> a.tofile('foo')
检查该文件后发现它的长度为24个字节,并且其内容与little-endian 64位IEEE 754浮点型相对应:
$ hexdump -C foo
00000000 00 00 00 00 00 00 f0 3f 00 00 00 00 00 00 00 40 |.......?.......@|
00000010 00 00 00 00 00 00 08 40 |.......@|
00000018