Search and write to .txt file

Piet van Oostrum piet at
Tue Aug 11 15:30:12 CEST 2009

>>>>> Helvin <helvinlui at> (H) wrote:

>H> Hi everyone,
>H> I am writing some python script that should find a line which contains
>H> '1' in the data.txt file, then be able to move a certain number of
>H> lines down, before replacing a line. At the moment, I am able to find
>H> the line '1', but when I use to move, and then rewrite, what I
>H> write goes to the end of the .txt file, instead of being adjusted by
>H> my

>H> Do you know what way I should take?

>H> Data.txt is a file of 3 lines:
>H>    line1
>H>    line2
>H>    line3

>H> Code:

>H>    with open('data.txt', 'r+') as f:
>H>        firstread = f.readlines()   # Take a snapshot of initial file

>H>,0)    # Go back to beginning and search
>H>        for line in f:
>H>            print line
>H>            if line.find('1'):
>H>                print 'line matched'
>H>      ,1)       # Move one space along
>H>                f.write('house\n')     # f.write overwrites the exact
>H> number of bytes.
>H>                break                    # leave loop once '1' is found

Mixing an iterator on the file with direct calls (seek/write) isn't
going to work. The iterator does read ahead which causes the file
position not to be what you think it is.


>>> with open('data.txt', 'r+') as f:
...   for line in f:
...       print line, f.tell()

Piet van Oostrum <piet at>
URL: [PGP 8DAE142BE17999C4]
Private email: piet at

More information about the Python-list mailing list