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

Patrick Phalen python-tutor@teleo.net
Sat, 21 Aug 1999 21:33:05 -0700


On Sun, 22 Aug 1999, Sean Conway wrote:
> 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)

Sean,

The python interactive interpreter is your friend when you're first
learning to manipulate files and their contents.

Try entering this *from the interactive interpreter*:

>>>data = open('/home/nconway/python/data', 'r').read()
>>>data

Take a look at what you get and then think about what you might need to
do in your program.