liveBook · Manning

Struct.unpack

As explained in The Quick Python Book, Fourth Edition

struct.unpack is a struct-module function that parses a packed byte sequence according to a format string and returns the resulting Python values as a tuple.

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

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains the call, tuple result, record sizing, and malformed-record failure, while deferring detailed format documentation.
Examples
Demonstrates reading records formatted as hd7s and producing (42, 3.14, b'goodbye').
What it assumes
Assumes familiarity with binary files, file reads, and format strings; supplies the needed record-size calculation.
What you can do after
Apply it to decode fixed-size binary file records into tuples of Python values.
How it connects
Connects struct.unpack with struct.pack, struct.calcsize, format strings, binary files, and endianness.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.