contentsthe standard library struct module is more powerful alternative the struct module provides calls to pack and unpack binary dataas though the data was laid out in -language struct declaration it is also capable of composing and decomposing using any endian-ness you desire (endian-ness determines whether the most significant bits of binary numbers are on the left or right sidebuilding binary datafilefor instanceis straightforward--pack python values into byte string and write them to file the format string here in the pack call means big-endian (>)with an integerfour-character stringhalf integerand floating-point numberimport struct data struct pack('> shf' 'spam' data '\ \ \ \ spam\ \ ?\ \xf \xb file open('data bin''wb'file write(data file close(notice how the struct module returns bytes stringwe're in the realm of binary data herenot textand must use binary mode files to store as usualpython displays most of the packed binary data' bytes here with \xnn hexadecimal escape sequencesbecause the bytes are not printable characters to parse data like that which we just producedread it off the file and pass it to the struct module with the same format string--you get back tuple containing the values parsed out of the string and converted to python objectsimport struct file open('data bin''rb'bytes file read(values struct unpack('> shf'datavalues ( 'spam' parsed-out strings are byte strings againand we can apply string and bitwise operations to probe deeperbin(values[ ' values[ ]list(values[ ])values[ ][ ( 'spam'[ ] accessing bits and bytes also note that slicing comes in handy in this domainto grab just the four-character string in the middle of the packed binary data we just readwe can simply slice it out numeric values could similarly be sliced out and then passed to struct unpack for conversionbytes '\ \ \ \ spam\ \ ?\ \xf \xb bytes[ : 'spam file and directory tools