Numpy fromfile的两个实现



我正在尝试更新一些在方法中使用np.fromfile的遗留代码。当我尝试搜索此方法的numpy源时,我只能找到np.core.records.fromfile,但是当您搜索文档时,您可以找到np.fromfile。看看这两种方法,你可以看到它们有不同的kwargs,这让我觉得它们完全是不同的方法。

我的问题是:

1( np.fromfile的来源在哪里?

2(为什么同名下有两个不同的功能?如果您不注意差异,这显然会令人困惑,因为两者的行为不同。具体来说,如果您尝试读取的字节数超过文件包含的字节数,而np.fromfile则不会np.core.records.fromfile将引发错误。您可以在下面找到一个最小示例。

In [1]: import numpy as np
In [2]: my_bytes = b'x04x00x00x00xacx92x01x00xb2x91x01'
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.fromfile上使用help,你会发现一些非常...有益的:

Help on built-in function fromfile in module numpy.core.multiarray:
fromfile(...)
    fromfile(file, dtype=float, count=-1, sep='')
    Construct an array from data in a text or binary file.
    A highly efficient way of reading binary data with a known data-type,
    as well as parsing simply formatted text files.  Data written using the
    `tofile` method can be read using this function.

据我所知,这是用 C 实现的,可以在这里找到。

如果您尝试保存和加载二进制数据,则不应再使用np.fromfile。您应该使用 np.savenp.load,它们将使用与平台无关的二进制格式。

最新更新