[Tutor] Read and write from file

Bob Gailer bgailer at alum.rpi.edu
Wed Aug 25 20:55:41 CEST 2004


At 12:29 PM 8/25/2004, Øyvind wrote:
>Hello,
>
>    I am trying to read and write from a file, but I cannot get it to do so.
>
>The file has the following lines:
>
>1
>2
>3
>4
>5
>6
>7
>8
>9
>
>I open the file with
>fil = open('d:\\test.txt','rw')
>(I have tried, r, w, w+, r+, a and a+ as well.)
>
>fil.readline()
>gives
>'1\n'
>and so forth.
>
>If I try
>fil.write("test")
>it skips to 4. Why? And why does not the file contain the word test? I
>ahve tried both fil.close and fil.flush without any luck.
>
>What I really want to do is to read the first line, 1, then replace that
>with something else, or remove it. Then read 2, and remove it, then read 3
>and change it and so forth. How can I read, write and modify at the same
>time? So far I have only been able to either read or write, but not both.

Use 'r+', and close and repoen the file to see the changes.

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625 home
720 938 2625 cell 



More information about the Tutor mailing list