Search and write to .txt file

Helvin helvinlui at
Tue Aug 11 13:22:13 CEST 2009

Hi everyone,

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

Do you know what way I should take?

Data.txt is a file of 3 lines:


   with open('data.txt', 'r+') as f:
       firstread = f.readlines()   # Take a snapshot of initial file,0)    # Go back to beginning and search
       for line in f:
           print line
           if line.find('1'):
               print 'line matched'
     ,1)       # Move one space along
               f.write('house\n')     # f.write overwrites the exact
number of bytes.
               break                    # leave loop once '1' is found,0)              # Go back to beginning, and read
data.txt again
       lastread = f.readlines()

       print 'firstread is', firstread
       print 'lastread is', lastread

This shouldn't be too difficult, but I don't know how. > <
Help appreciated!

More information about the Python-list mailing list