Search code examples
python-3.xfile-iowhile-loopbinaryfilesblender

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


I've been working on an import script and have managed to hammer out most of the issues up until this point-I need to loop through the vertices until I reach a byte header that proceeds them but despite trying re.match, re.search, and != the while loop simply continues till the end of the file. I'm not sure where I went wrong given regex works with the if statement prior to this section of code.

while re.match(b'\x05\xC0.x\6E', 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)

Solution

  • The code is reading 4 bytes each time, but the pattern is 6 bytes-long.

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

    The pattern will never match. That's why it continue until the end of the file.

    IMHO, you mean this: (swapping the last \ and x)

    b'\x05\xC0.\x6E'
    

    >>> import re
    >>> re.match(b'\x05\xC0.x\6E', 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'>