incrementing string/hex value from file and write back

M

Matthias Güntert

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
 
S

Simon Forman

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


Check this out:

In [1]: val = '0C'

In [2]: val.encode('hex')
Out[2]: '3043'

That's not what you want. Try this:

In [3]: int(val, 16)
Out[3]: 12

And to convert an int to a hex string.

In [4]: '%x' % 13
Out[4]: 'd'

The interpreter has a help() function that gives you quick access to
information about python objects:
Help on method_descriptor:

encode(...)
S.encode([encoding[,errors]]) -> object

Encodes S using the codec registered for encoding. encoding
defaults
to the default encoding. errors may be given to set a different
error
handling scheme. Default is 'strict' meaning that encoding errors
raise
a UnicodeEncodeError. Other possible values are 'ignore',
'replace' and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that is able to handle UnicodeEncodeErrors.
Help on class int in module __builtin__:

class int(object)
| int(x[, base]) -> integer
|
| Convert a string or number to an integer, if possible. A floating
point
| argument will be truncated towards zero (this does not include a
string
| representation of a floating point number!) When converting a
string, use
| the optional base. It is an error to supply a base when
converting a
| non-string. If the argument is outside the integer range a long
object
| will be returned instead.
|
| Methods defined here:
|
....


Unfortunately you can't use it on the '%' string formatting
operator...
SyntaxError: invalid syntax

So here's a link to the docs:
http://docs.python.org/library/stdtypes.html#string-formatting-operations


HTH,
~Simon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top