Skip to main content
 首页 » 编程设计

python之如何分块循环遍历 Python 中的二进制文件

2025年05月04日21cmt

我正在尝试使用 Python 遍历一个充满 8 字节记录的长二进制文件。

每条记录的格式为[ uint16 | uint16 | uint32]
(在结构格式中是 "HHI")

显然每个 8 字节的 block 都被视为 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) 

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

请您参考如下方法:

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

因此您可以使用 functools.partial 创建偏函数(或使用 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