Python struct.unpack 二进制文件

Python struct.unpack binary file

我正在使用 struct.unpack 将文件的第 11 个字节读取到第 21 个字节,后者表示应该读取 'SNA' 的字段。该字段是 'populated as BCS-A where it is left justified and padded to the right boundary with BCS spaces'。由于该字段的长度为 10 个字节,因此我的格式字符串为“10s”。但是,根据提到的输出,剩余的 7 个字节是空格。为了消除这些空格,我使用了 strip。不幸的是,这仍然会产生 'SNA\x00'。我究竟做错了什么?

field = struct.unpack('10s',data[start:stop])
field[0].strip() (since the output of a strut.unpack is a tuple)

您的数据不符合您指定的标准。要么联系你的数据供应商并让他们修复他们的错误,要么更慷慨地定义 "space"。如果您想接受该数据,您可以这样做:

field[0].strip(' \t\n\x00')

或者,接受度更有限:

field[0].strip().rstrip('\x00')