Simple File I/O Question

Grant Edwards ge at nowhere.none
Fri Jul 14 09:16:12 EDT 2000


In article <8klm17$1se at quail.swcp.com>, Charlie Sorsby wrote:
>In article <4ymb5.894$6E.112638 at ptah.visi.com>,
>Grant Edwards <ge at nowhere.none> wrote:
>= In article <396DF13A.97CC3F5E at bioeng.ucsd.edu>, Curtis Jensen wrote:
>= >I know this should be simple, but....  I have a variable that holds an
>= >int.  I want to write it to a file.  The following code:
>= >
>= >var = 5
>= >f = open('foo','w')
>= >f.write(var)
>= >
>= >gives this error:
>= >TypeError: read-only buffer, int
>= 
>= the write method only accepts strings as parameters, so you've
>= got to convert whatever you want to write to a string before
>= passing it to write()
>= 
>= try this:
>= 
>=   f.write(str(var))
>=     or
>=   f.write("The value of 'var' is %d\n" % var)
>
>If I may add my own question to that of the original poster:
>
>What if one needs to send an int to a device that will use it
>and needs it to be an int not a string?  E.g. suppose I need to
>send a hex int via the serial port (/dev/cuaa0) to some device?  Is
>this not possible in python?

To write the hex values 0x12 0x34 0x56:

f.write('\x12\x43\x56')

-- 
Grant Edwards                   grante             Yow!  FROZEN ENTREES may
                                  at               be flung by members of
                               visi.com            opposing SWANSON SECTS...



More information about the Python-list mailing list