how to convert from network to host byte order

Evan xdicry at gmail.com
Thu Mar 5 07:26:30 EST 2009


Hello ~

I'm new with python,  what my problem is, I have a binary file, I want
to read first 2 bytes and convert it to host byte order, then write it
to another file.

I try to use 'socket' and 'struct', but somehow i can not get it
working fine:

for example, totally I'm not sure if my steps is correct or not:
++++++++++++++++++++++++++++++++++++++++++++++++
>>> import socket
>>> f=open('a.bin','rb')
>>> f.read(2)
'\x04\x00'

>>> f.seek(0)
>>> st=f.read(2)
>>> e=open('test.bin','w+b')
>>> e.write(socket.ntohs(struct.unpack('H',st[:2])[0]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument 1 must be string or read-only buffer, not int
+++++++++++++++++++++++++++++++++++++++++++++++++

It failed due to the parameter is 'int', not 'str' in write function.
but how can i do that?

Thanks,
Evan



More information about the Python-list mailing list