How to loop over a binary file in Python in chunks

后端 未结 3 766
青春惊慌失措
青春惊慌失措 2021-01-22 00:13

I\'m trying to use Python to loop over a long binary file filled with 8-byte records.

Each record has the format [ uint16 | uint16 | uint32 ]
(which

3条回答
  •  天命终不由人
    2021-01-22 00:48

    f.read(len) only returns a byte string. Then raw will be a single byte.

    The correct way of looping is:

    with open(fname, 'rb') as f:
        while True:
            raw = f.read(8)
            if len(raw)!=8:
                break # ignore the incomplete "record" if any
            record = struct.unpack("HHI", raw )
            print(record)
    

提交回复
热议问题