numpy memmap忽略EOF

2024-05-14 15:06:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将一个二进制文件映射到内存,内存有一个自定义的数据类型。我是这样做的:

np.memmap(filename=f, dtype=my_sample_dtype, mode='r')

有时,二进制文件的结尾会被切掉,因为写入它的进程意外地结束了。在这种情况下,numpy抱怨:

ValueError: Size of available data is not a multiple of the data-type size.

现在我可以截短磁盘上的文件,使其成为数据类型大小的倍数,但我想要一个不需要接触原始文件的解决方案。我能告诉numpy忽略文件末尾不完整的元素吗?你知道吗


Tags: 文件ofsample内存numpydatamodemy
1条回答
网友
1楼 · 发布于 2024-05-14 15:06:58

答案就在np.memmap documentation里:

shape : tuple, optional

The desired shape of the array. If mode == 'r' and the number of remaining bytes after offset is not a multiple of the byte-size of dtype, you must specify shape.

因此,只需使用常规Python函数来获取文件大小,计算文件包含多少完整元素,并将其作为shape传递。您得到的异常将不再发生。如果查看源代码,很容易理解为什么:https://github.com/numpy/numpy/blob/ab49be1/numpy/core/memmap.py-只有在shape is None时才能抛出异常。你知道吗

相关问题 更多 >

    热门问题