cha*_*com 2 python matlab numpy scipy
我正在转向Matlab到NumPy/SciPy,似乎np.fromfile和ndarray.tofile分别在matlab中对fread和fwrite进行了修改.
为了测试这些API,我首先创建了一个二进制文件,其中包含五个整数{1,2,3,4,5},采用二进制'int32'格式.
然后,我使用np.fromfile读取此文件.
In [365]:
in_file = open('12345.bin', 'rb'); x = np.fromfile(in_file, 'int32'); in_file.close()
Run Code Online (Sandbox Code Playgroud)
我检查它已成功读取,如下所示:
In [367]:
x
Out[366]:
array([1, 2, 3, 4, 5], dtype=int32)
Run Code Online (Sandbox Code Playgroud)
现在,我将其写为具有不同名称的文件.我的期望是这个输出文件应该与原始输入文件完全相同,即'12345.bin'.
In [368]:
out_file = open('12345out.bin', 'wb'); x.tofile(out_file, 'int32'); out_file.close()
Run Code Online (Sandbox Code Playgroud)
但令人惊讶的是,'12345out.bin'的大小是25个字节,而'12345.bin'是20个字节.出了点问题.我打开'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)
Run Code Online (Sandbox Code Playgroud)
因此,从上面的结果来看,我们发现某些事情是完全错误的.Coud有谁请帮助我,我做错了什么?
tofile不需要类型参数(这是它不是一个很好的工具的原因之一,因为它不保留类型信息).所以,当你这样做
x.tofile(out_file, 'int32')
Run Code Online (Sandbox Code Playgroud)
你实际上是说你希望以文本格式使用字符串 "int32"作为分隔符:
>>> x = np.arange(1,6,dtype=np.int32)
>>> x.tofile(open("tmp.dat", "wb"), "int32")
>>> open("tmp.dat","rb").read()
b'1int322int323int324int325'
Run Code Online (Sandbox Code Playgroud)
代替:
>>> 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])
Run Code Online (Sandbox Code Playgroud)
(请注意,我懒得使用with块来打开和关闭文件,因为我应该这样做.)