python - 如何使用 `np.fromfile` 从二进制文件中读取连续数组?

标签 python numpy

我想用 Python 读取二进制文件,其确切布局存储在二进制文件本身中。

该文件包含一系列二维数组,每个数组的行和列维度存储为一对整数,位于其内容之前。我想连续读取文件中包含的所有数组。

我知道这可以用 f = open("myfile", "rb")f.read(numberofbytes) 来完成,但这很笨拙,因为然后我需要将输出转换为有意义的数据结构。我想将 numpy 的 np.fromfile 与自定义 dtype 一起使用,但还没有找到一种方法来读取文件的一部分,让它保持打开状态,然后继续阅读修改后的 dtype

我知道我可以多次使用 osf.seek(numberofbytes, os.SEEK_SET)np.fromfile,但这将意味着在文件中有很多不必要的跳跃。

简而言之,我想要 MATLAB 的 fread(或者至少像 C++ ifstream read)。

执行此操作的最佳方法是什么?

最佳答案

您可以将打开的文件对象传递给np.fromfile ,读取第一个数组的维度,然后读取数组内容(再次使用 np.fromfile),并对同一文件中的其他数组重复该过程。

例如:

import numpy as np
import os

def iter_arrays(fname, array_ndim=2, dim_dtype=np.int, array_dtype=np.double):

    with open(fname, 'rb') as f:
        fsize = os.fstat(f.fileno()).st_size

        # while we haven't yet reached the end of the file...
        while f.tell() < fsize:

            # get the dimensions for this array
            dims = np.fromfile(f, dim_dtype, array_ndim)

            # get the array contents
            yield np.fromfile(f, array_dtype, np.prod(dims)).reshape(dims)

示例用法:

# write some random arrays to an example binary file
x = np.random.randn(100, 200)
y = np.random.randn(300, 400)

with open('/tmp/testbin', 'wb') as f:
    np.array(x.shape).tofile(f)
    x.tofile(f)
    np.array(y.shape).tofile(f)
    y.tofile(f)

# read the contents back
x1, y1 = iter_arrays('/tmp/testbin')

# check that they match the input arrays
assert np.allclose(x, x1) and np.allclose(y, y1)

如果数组很大,您可以考虑使用 np.memmap使用 offset= 参数代替 np.fromfile 以获取数组内容作为内存映射,而不是将它们加载到 RAM 中。

关于python - 如何使用 `np.fromfile` 从二进制文件中读取连续数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31214916/

相关文章:

python - 如何使用 Telegram Python 机器人发送粗体文本

python - 如何将 2D 网格化点云插值到连续区域?

python - 如何在 Keras 中将密集层归零?

python - 最小化以numpy数组为参数的python函数

python - 是否有更矢量化的方式来沿轴执行 numpy.outer ?

python - 有效地居中和叠加 numpy 数组

numpy - 基于放置在像素上的小掩码分配值

python - 在python中使用字符串+ key 计算SHA哈希

python - python的ord()函数的对立面是什么?

python - 使用 SqlAlchemy 和 Alembic 创建部分索引