Skip to content

struct

The Python struct module converts between Python values and packed binary records stored in bytes objects, following the layout of C structs. Compact format strings describe each record field by field, including its byte order.

The module is the standard tool for reading and writing fixed binary layouts, such as file headers, network packets, and data exchanged with C code. For whole arrays of a single numeric type, the array module is often a better fit, and ctypes covers calling C libraries directly.

Here’s a quick example:

Language: Python
>>> import struct

>>> struct.pack(">hI", 1023, 7)
b'\x03\xff\x00\x00\x00\x07'
>>> struct.unpack(">hI", b"\x03\xff\x00\x00\x00\x07")
(1023, 7)

The format ">hI" describes a big-endian record with a 2-byte signed short followed by a 4-byte unsigned int, so the round trip returns the original values.

Key Features

  • Packs Python integers, floats, Booleans, and byte strings into a bytes object with pack().
  • Unpacks binary data back into a tuple of Python values with unpack().
  • Selects byte order, field sizes, and alignment with a leading @, =, <, >, or ! character.
  • Reports the exact size of a record format with calcsize().
  • Reads and writes records in place inside existing buffers with unpack_from() and pack_into().
  • Iterates over a stream of equal-sized records with iter_unpack().
  • Compiles a format once for repeated use through the Struct class.

Frequently Used Classes and Functions

Object Type Description
struct.pack() Function Returns a bytes object containing the given values packed according to a format string.
struct.unpack() Function Returns a tuple of values unpacked from a buffer whose size matches the format exactly.
struct.calcsize() Function Returns the size in bytes of the record that a format describes.
struct.unpack_from() Function Unpacks values from a buffer starting at a given offset.
struct.pack_into() Function Packs values into a writable buffer starting at a given offset.
struct.iter_unpack() Function Returns an iterator that unpacks consecutive equal-sized records from a buffer.
struct.Struct Class Compiles a format string into an object with its own packing methods and a .size attribute.
struct.error Exception Signals invalid formats, out-of-range values, and buffers of the wrong size.

Examples

Shows how the byte-order prefix changes the packed bytes for the same value:

Language: Python
>>> import struct

>>> struct.pack("<h", 1023)
b'\xff\x03'
>>> struct.pack(">h", 1023)
b'\x03\xff'

Unpacks a fixed-width record into a named tuple for readable field access:

Language: Python
>>> import struct
>>> from collections import namedtuple

>>> Student = namedtuple("Student", "name serial school grade")
>>> record = b"raymond   \x32\x12\x08\x01\x08"
>>> Student._make(struct.unpack("<10sHHb", record))
Student(name=b'raymond   ', serial=4658, school=264, grade=8)

Rejects a value that doesn’t fit in the chosen field size:

Language: Python
>>> import struct

>>> struct.pack(">h", 99999)
Traceback (most recent call last):
  ...
struct.error: 'h' format requires -32768 <= number <= 32767

Compares native alignment, which inserts padding that depends on the platform and compiler, with standard mode, which never pads. The native size of 8 shown here is typical of mainstream platforms:

Language: Python
>>> import struct

>>> struct.calcsize("@ci")
8
>>> struct.calcsize("<ci")
5

To see both effects together, pick a prefix below and watch how the same three values land in the packed bytes, including any alignment padding:

Interactive diagram — enable JavaScript to view.

Common Use Cases

  • Parsing headers of binary file formats such as images, audio, and archives
  • Building and decoding network protocol messages in network byte order
  • Writing compact fixed-size records to log files or data files
  • Exchanging data with C programs and extensions that expect a specific memory layout
  • Reading sensor or device output delivered as raw bytes

Real-World Example

Say a data logger stores each sensor reading as a fixed-size little-endian record holding a Unix timestamp, a sensor ID, and a temperature. The following script writes a few readings to a binary file and then reads them back:

Language: Python Filename: sensor_log.py
import struct
from pathlib import Path

READING = struct.Struct("<IHf")
log_path = Path("readings.bin")

readings = [
    (1_760_000_000, 1, 21.5),
    (1_760_000_060, 2, 19.25),
    (1_760_000_120, 1, 21.75),
]
log_path.write_bytes(b"".join(READING.pack(*row) for row in readings))

data = log_path.read_bytes()
print(f"{len(data)} bytes, {READING.size} bytes per record")
for timestamp, sensor_id, celsius in READING.iter_unpack(data):
    print(f"{timestamp}  sensor {sensor_id}: {celsius:.2f} C")

Running the script prints the decoded records:

Language: Shell
$ python sensor_log.py
30 bytes, 10 bytes per record
1760000000  sensor 1: 21.50 C
1760000060  sensor 2: 19.25 C
1760000120  sensor 1: 21.75 C

The compiled Struct fixes the record layout in one place, so every record takes exactly ten bytes and iter_unpack() can walk the file without any manual offset arithmetic.

Bytes Objects: Handling Binary Data in Python

Tutorial

Bytes Objects: Handling Binary Data in Python

In this tutorial, you'll learn about Python's bytes objects, which help you process low-level binary data. You'll explore how to create and manipulate byte sequences in Python and how to convert between bytes and strings. Additionally, you'll practice this knowledge by coding a few fun examples.

intermediate python

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Martin Breuss • Updated Nov. 21, 2026