struct.unpack parses a packed byte sequence according to a format string and returns the decoded Python values as a tuple. It is useful for reading fixed-format binary records. section 13.7
Use the function as follows:
- Determine the record format, then call struct.calcsize(format) to find how many bytes belong to one record. section 13.7
- Read exactly that many bytes and pass both the format string and byte sequence to struct.unpack(format, record). section 13.7
- The result is a tuple containing one Python value for each format-string field; an incorrectly sized final record raises an error. section 13.7
import struct
record_format = 'hd7s'
record_size = struct.calcsize(record_format)
result_list = []
with open("data", 'rb') as input:
while True:
record = input.read(record_size) #1
if not record: #2
break
result_list.append(struct.unpack(record_format, record)) #3
print(result_list)
[(42, 3.14, b'goodbye')]]
#1 Reads in a single record
#2 Checks to see if record is empty
#3 Unpacks record into a tuple; appends to results
A complete loop calculates the record size, reads one binary record at a time, stops at end-of-file, and appends each unpacked tuple. section 13.7
