pythonwindowsstructbinarypacked

Why some values make struct.pack and struct.unpack to fail on Windows?


When I use struct.pack() to convert a python integer to C structs (and write it to a file) and then struct.unpack() to reverse the conversion I get usually the original value...but not always. Why? Are there some unmanageable values?

Example:

import struct
fileName ='C:/myFile.ext'
formatCode = 'H'
nBytes = 2
tries = range(8,12)
for value in tries:
    newFile = open(fileName, mode='w+')
    myBinary = struct.pack( formatCode, value )
    newFile.write(myBinary)
    newFile.close()

    infile = open(fileName,'rb')
    bytesRead = infile.read(nBytes)
    newValue = struct.unpack( formatCode, bytesRead )
    print value, 'equal', newValue[0]
    infile.close()

returns:

8 equal 8
9 equal 9
10 equal 2573
11 equal 11
12 equal 12

It happens not only with integer (2 bytes: format 'H') but also with other types and values. Value 10 gives this 'error' if I pack as integer, but not as float, but working with float I get errors with other values.

If the problem is that I cannot convert int number 10 to this packed struct, what alternative do I have to write this value in the file (packed)?


Solution

  • You forgot to specify binary mode when writing. wb+ not w+.