incrementing string/hex value from file and write back

Simon Forman sajmikins at gmail.com
Thu Aug 20 23:35:12 CEST 2009


On Aug 20, 5:08 pm, Matthias Güntert <MatzeGuent... 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')
> 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....


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(str.encode)
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(int)
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...

>>> help(%)
SyntaxError: invalid syntax

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


HTH,
~Simon



More information about the Python-list mailing list