[Tutor] Read and write from file

Kent Johnson kent_johnson at skillsoft.com
Wed Aug 25 22:17:16 CEST 2004

You can't just overwrite the lines in place because they are different 
lengths. Files aren't that smart - you need to read the file and re-write 
it. You should look at the fileinput module, it makes this kind of 
line-by-line filtering of a file pretty simple. For example, if test.txt 
contains four lines:

and I run this program:
import fileinput
for line in fileinput.input('test.txt', inplace=1, backup='.bak'):
     if line == '1\n':
         print 'test'
     elif line == '3\n':
         print '3xx'
         print line,

then test.txt will contain this:

and test.bak will have the original contents of test.txt


At 08:29 PM 8/25/2004 +0200, Øyvind wrote:
>    I am trying to read and write from a file, but I cannot get it to do so.
>The file has the following lines:
>I open the file with
>fil = open('d:\\test.txt','rw')
>(I have tried, r, w, w+, r+, a and a+ as well.)
>and so forth.
>If I try
>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.
>Thanks in advance....
>This email has been scanned for viruses & spam by Decna as - www.decna.no
>Denne E-post er sjekket for virus & spam av Decna as - www.decna.no
>Tutor maillist  -  Tutor at python.org

More information about the Tutor mailing list