尝试 while-loop 我的方式通过一个二进制文件直到某个字节但循环永远不会结束

Trying to while-loop my way through a binary file until a certain byte but the loop never ends

我一直在研究一个导入脚本,并设法解决了到目前为止的大部分问题——我需要循环遍历顶点,直到我到达一个处理它们的字节头,但尽管尝试了 re.match、re.search 和 != while 循环简单地继续到文件末尾。鉴于正则表达式在这部分代码之前使用 if 语句,我不确定哪里出错了。

while re.match(b'\x05\xC0.xE', byte) is None:

            #Fill the vertex list by converting byte to its little endian float value
            vertex[0] = struct.unpack('<f', byte)
            byte = f.read(4)
            vertex[1] = struct.unpack('<f', byte)
            byte = f.read(4)
            vertex[2] = struct.unpack('<f', byte)

            #Append the vertices list with the completed vertex
            vertices.append(vertex)
            vertex_count += 1

            #Read in what will either be the next X coordinate or a file header
            byte = f.read(4)

代码每次读取 4 个字节,但模式是 6 个字节长。

>>> len(b'\x05\xC0.xE')
6
>>> b'\x05\xC0.xE' == b'\x05' + b'\xC0' + b'.' + b'x' + b'' + b'E'
True

模式永远不会匹配。这就是它一直持续到文件末尾的原因。

恕我直言,你的意思是:(交换最后一个 \x

b'\x05\xC0.\x6E'

>>> import re
>>> re.match(b'\x05\xC0.xE', b'\x05\xC0\x00\x6E')  # no match
>>> re.match(b'\x05\xC0.\x6E', b'\x05\xC0\x00\x6E')  # match
<_sre.SRE_Match object; span=(0, 4), match=b'\x05\xc0\x00n'>