file handling when creating custom binary file formats it is wise to create magic number to identify your file typeand version number to identify the version of the file format in use here are the definitions used in the convert-incidents py programmagic "aib\ format_version "\ \ we have used four bytes for the magic number and two for the version endianness is not an issue because these will be written as individual bytesnot as the byte representations of integersso they will always be the same on any processor architecture to write and read raw binary data we must have some means of converting python objects to and from suitable binary representations most of the functionality we need is provided by the struct modulebriefly described in the sidebar "the struct module )and by the bytes and bytearray data typesbriefly described in the sidebar "the bytes and bytearray data types( the bytes and bytearray classesmethods are listed in tables and unfortunatelythe struct module can handle strings only of specified lengthand we need variable length strings for the report and aircraft idsas well as for the airportthe aircraft typeand the narrative texts to meet this need we have created functionpack_string()which takes string and returns bytes object which contains two componentsthe first is an integer length countand the second is sequence of length count utf- encoded bytes representing the string' text since the only place the pack_string(function is needed is inside the export_binary(functionwe have put the definition of pack_string(inside the export_binary(function this means that pack_string(is not visible outside the export_binary(functionand makes clear that it is just local helper function here is the start of the export_binary(functionand the complete nested pack_string(functiondef export_binary(selffilenamecompress=false)def pack_string(string)data string encode("utf "format "< { }sformat(len(data)return struct pack(formatlen(data)datacharacter encodings the str encode(method returns bytes object with the string encoded according to the specified encoding utf- is very convenient encoding because it can represent any unicode character and is especially compact when representing ascii characters (just one byte eachthe format variable is set to hold struct format based on the string' length for examplegiven the string local functions