【发布时间】:2017-08-12 04:12:41
【问题描述】:
我正在尝试更新一些在方法中使用np.fromfile 的遗留代码。当我尝试搜索该方法的 numpy 源时,我只找到 np.core.records.fromfile,但是当您搜索文档时,您可以找到 np.fromfile。看看这两种方法,你会发现它们有不同的 kwargs,这让我觉得它们完全是不同的方法。
我的问题是:
1) np.fromfile 的来源在哪里?
2) 为什么同一个名字下有两个不同的函数?如果您不注意两者的行为差异,这显然会让人感到困惑。具体来说,np.core.records.fromfile 将引发错误,如果您尝试读取的字节数超过文件包含的字节数,而 np.fromfile 则不会。您可以在下面找到一个最小的示例。
In [1]: import numpy as np
In [2]: my_bytes = b'\x04\x00\x00\x00\xac\x92\x01\x00\xb2\x91\x01'
In [3]: with open('test_file.itf', 'wb') as f:
f.write(my_bytes)
In [4]: with open('test_file.itf', 'rb') as f:
result = np.fromfile(f, 'int32', 5)
In [5]: result
Out [5]:
In [6]: with open('test_file.itf', 'rb') as f:
result = np.core.records.fromfile(f, 'int32', 5)
ValueError: Not enough bytes left in file for specified shape and type
【问题讨论】:
-
是的,您正在链接到
np.core.records.fromfile的源代码,它专门用于处理记录数组。 -
@juanpa.arrivillaga 我知道这一点。不幸的是,这是我可以在源代码中找到的唯一实现的 fromfile 声明。我想知道在哪里可以找到
np.fromfile的来源 -
records版本的本质是创建一个dtype和shape正确的接收者数组,并使用二进制文件readinto方法将字节加载到它的.data属性中。 -
core.records的东西是numpy的死水。structured arrays,没有records覆盖更常见,通常由genfromtxt从csv文件生成。
标签: python python-3.x numpy binary fromfile