1

我正在尝试更新一些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
4

1 回答 1

4

如果你使用helponnp.fromfile你会发现一些非常...有用的东西:

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.saveand np.loadwhich 将使用与平台无关的二进制格式。

于 2017-03-20T18:35:10.543 回答