incrementing string/hex value from file and write back

Ethan Furman ethan at stoneleaf.us
Thu Aug 20 17:36:41 EDT 2009


[fixed top-posting]

Rami Chowdhury wrote:
> On Thu, 20 Aug 2009 14:08:34 -0700, Matthias Güntert  
> <MatzeGuentert at gmx.de> 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')
> 
> That's the crucial line -- it's returning a new integer,  which you are
> re-binding to val. If you then did:
> 
>   val = val + 1
> 
> you'd be fine, and could then write val back to your file :-)
> 

.encode('hex') is returning a string -- attempting to add one to it will 
raise the same error the OP is getting below.

To get a number you can do (after reading val from the file):

val = int(val, '16') # convert from base 16
val += 1             # increment
val = "%X" % val     # back to heg digits

and then write it back out again.  Don't forget to close and reopen the 
file for writing.  :)

~Ethan~

>> 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....




More information about the Python-list mailing list