incrementing string/hex value from file and write back

Mark Lawrence breamoreboy at yahoo.co.uk
Thu Aug 20 23:36:37 CEST 2009


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')
val = int(val, 16) + 1
f.write('%02X' % val)
> 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....
> 


-- 
Kindest regards.

Mark Lawrence.




More information about the Python-list mailing list