Matthias Güntert wrote:
Hello guys
I would like to read a hex number from an ASCII file, increment it and
write it back.
How can this be performed?
I have tried several approaches:
my file serial.txt contains: 0C
----------------------------------
f = open('serial.txt', 'r')
val = f.read()
val = val.encode('hex')
print val
----------------------------------
--> 3043
----------------------------------
f = open('serial.txt', 'r')
val = f.read()
print val
val = val+1
----------------------------------
--> TypeError: cannot concatenate 'str' and 'int' objects
----------------------------------
f = open('serial.txt', 'rb')
val = f.read()
val = val + 1
----------------------------------
--> TypeError: cannot concatenate 'str' and 'int' objects
hm....
You don't say much to constrain the file. Is it always two characters
(nibbles) long? Or might it have a newline at the end? If it could be
multiple lines, is each line limited to 2 columns? or to 8 columns? or
no limit?
To interpret val as an integer, try new = int(val, 16)
Then to convert back to hex digits, try line = "%x" % (val+1)
For fancier conversions, look at binascii.unhexlify() and hexlify().
Look also at chr() and ord(). and str.format()
DaveA
--
http://mail.python.org/mailman/listinfo/python-list