首页 > 解决方案 > 如何在Python中以块的形式循环二进制文件

问题描述

我正在尝试使用 Python 循环一个长的二进制文件,其中包含 8 字节的记录。

每条记录都有格式[ uint16 | uint16 | uint32 ]
"HHI"在结构格式中)

显然,每个 8 字节块都被视为int,而不是 8 字节数组,然后导致struct.unpack调用失败

with open(fname, "rb") as f:
    sz=struct.calcsize("HHI")
    print(sz)                # This shows 8, as expected 
    for raw in f.read(sz):   # Expect this should read 8 bytes into raw
        print(type(raw))     # This says raw is an 'int', not a byte-array
        record=struct.unpack("HHI", raw ) # "TypeError: a bytes-like object is required, not 'int'"
        print(record)

如何将我的文件读取为一系列结构,并将它们分别打印出来?

标签: pythonbinary-data

解决方案


内置的iter,如果传递了一个可调用对象和一个标记值,将重复调用该可调用对象,直到返回标记值。

因此,您可以使用functools.partial(或使用 a )创建一个部分函数lambda并将其传递给iter,如下所示:

with open('foo.bin', 'rb') as f:
    chunker = functools.partial(f.read, 8)
    for chunk in iter(chunker, b''):      # Read 8 byte chunks until empty byte returned
        # Do stuff with chunk

推荐阅读