[Tutor] File object, r/w (simple)

Sean Conway seanconway@home.com
Sun, 22 Aug 1999 00:03:03 -0700


Hello everyone.

I just recently started programming, and have decided to use Python after
looking at C and Perl. I have encounted a simple problem that I can't seem
to solve. This problem occurs in this situation - I am trying to read an
integer from a file, add 1 to the integer, and then write the modified value
back to the same file. Here is the code I am using (btw, the file will
initially be "0", that is all):

import string
dataFile = open('/home/nconway/python/data', 'r')
data = dataFile.read()
dataFile.close()
dataFile = open('/home/nconway/python/data', 'w')
print data
dataFile.write(string.atoi(data) + 1)
dataFile.close()

This generates the following error:

Traceback (innermost last):
  File "file-rw.py", line 8, in ?
    dataFile.write(string.atoi(data) + 1)

What am I doing wrong? Can someone tell me how to fix this? Furthermore,
what is the best way to do what I am trying to do? (i.e. most efficient, or
whatever).

Thanks in advance,

Sean Conway