ndarray.tofile的奇怪行为

时间:2015-12-29 04:22:32

标签: python matlab numpy scipy

我切换到Matlab到NumPy / SciPy,似乎np.fromfile和ndarray.tofile分别在matlab中反转fread和fwrite。

为了测试这些API,我首先在二进制' int32'中创建了一个包含五个整数{1,2,3,4,5}的二进制文件。格式。

然后,我使用np.fromfile读取此文件。

In [365]:

in_file = open('12345.bin', 'rb'); x = np.fromfile(in_file, 'int32'); in_file.close()

我检查了它已成功读取,如下所示:

In [367]:

x

Out[366]:
array([1, 2, 3, 4, 5], dtype=int32)

现在,我将其写为具有不同名称的文件。我的期望是这个输出文件应该与原始输入文件完全相同,即' 12345.bin'。

In [368]:


out_file = open('12345out.bin', 'wb'); x.tofile(out_file, 'int32'); out_file.close()

但令人惊讶的是,' 12345out.bin'是25个字节,而' 12345.bin'是20个字节。出了点问题。我打开了#12; 12345out.bin'如下:

In [369]:

in_file = open('12345out.bin', 'rb'); x2 = np.fromfile(in_file, 'int32'); in_file.close()

In [370]:

x2

Out[370]:
array([1953392945, 1764897331,  842232942, 1953392947, 1765028403,
        842232942], dtype=int32)

因此,从上面的结果来看,我们发现某些事情是完全错误的。 Coud有人请帮助我做错了吗?

1 个答案:

答案 0 :(得分:5)

tofile不需要type参数(这是它不是一个好工具的原因之一,因为它不保留类型信息)。所以当你这样做时

x.tofile(out_file, 'int32')

您实际上是说要以文本格式使用字符串 "int32"作为分隔符

>>> x = np.arange(1,6,dtype=np.int32)
>>> x.tofile(open("tmp.dat", "wb"), "int32")
>>> open("tmp.dat","rb").read()
b'1int322int323int324int325'

相反:

>>> x = np.arange(1,6,dtype=np.int32)
>>> x.tofile(open("tmp.dat", "wb"))
>>> open("tmp.dat","rb").read()
b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00'
>>> np.fromfile("tmp.dat", "int32")
array([1, 2, 3, 4, 5])

(请注意,我懒得使用with块来打开和关闭文件。)