python - 如何在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)
如何将我的文件读取为一系列结构,并将它们分别打印出来?
解决方案
内置的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
推荐阅读
- output-formatting - 如何更改 Niftynet 的输出格式?
- logstash - 如何阻止事件被发送到输出
- c# - 在 DataTemplate 和 Style 中定义不同的前景色
- swift - 在 Apple Watch 屏幕中间的表格前查看图像(刷新动画)
- case - 如果查询包含记录,则从查询创建 xml
- maven - 无法在 EJB 中添加 maven 依赖项 - Eclipse、websphere、maven
- scala - 是否可以在 spark.read.csv 中包含目录信息?
- apostrophe-cms - 控制台中的非托管模块错误
- python - 如何在 Python 中解释这种内存使用情况?
- c# - WPF 用户跟踪:Application Insight 与 HockeyApp 还是其他?