I'm working on an application writing binary data (ints, doubles, raw bytes) to a file.
Problem is, that the data is not actually written to the file the way I expect it to be:
>>> import struct
>>> import io
>>> out = io.open("123.bin", "wb+")
>>> format = "!i"
>>> data = struct.pack(format, 1)
>>> out.write(data)
4L
>>> data
'\x00\x00\x00\x01'
>>> out.close()
>>> infile = io.open("123.bin", "rb")
>>> instr = infile.read()
>>> instr
'\x00\x00\x00\x01'
>>> struct.unpack("!I", instr)
(1,)
So everything looks like it's working just fine. But upon closer examination, the 123.bin file has following contents:
$ hexdump 123.bin
0000000 0000 0100
0000004
So it looks like the bytes were swapped by io.write()!
The python documentation says, that io.write() accepts "given bytes or bytearray object", problem is, that struct.pack does return an str:
>>> type(struct.pack(format, 1))
<type 'str'>
So, what am I doing wrong? How do I convert str to bytes without any charset translation?