我想用Python读取二进制文件,其确切布局存储在二进制文件本身中。
该文件包含一个二维数组序列,每个数组的行和列尺寸在其内容之前存储为一对整数。我想连续读取文件中包含的所有数组。
我知道可以使用f = open("myfile", "rb")
和来完成此操作f.read(numberofbytes)
,但这非常笨拙,因为随后需要将输出转换为有意义的数据结构。我想将numpynp.fromfile
与自定义一起使用dtype
,但还没有找到一种方法来读取文件的一部分,使其保持打开状态,然后继续使用经过修改的进行读取dtype
。
我知道我可以使用os
到f.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。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句