Python - File struct

Introduction

Python struct module composes and parses packed binary data.

To create a packed binary data file, open it in 'wb' (write binary) mode.

Pass struct a format string and some Python objects.

The format string used here means pack as a 4-byte integer, a 4-character string, and a 2-byte integer, all in big-endian form:

Demo

F = open('data.bin', 'wb')                     # Open binary output file 
import struct 
data = struct.pack('>i4sh', 7, b'test', 8)     # Make packed binary data 
print( data )

F.write(data)                                  # Write byte string 
F.close()# w w w  . j a  v  a  2 s. co  m

Result

Python creates a binary bytes data string, then we write out to the file.

To parse the values to Python objects, read the string back and unpack it using the same format string.

Python extracts the values into normal Python objects: integers and a string:

Demo

import struct 
F = open('data.bin', 'rb') 
data = F.read()                                # Get packed binary data 
print( data )

values = struct.unpack('>i4sh', data)          # Convert to Python objects 
print( values )

Result