Search and write to .txt file

Kushal Kumaran kushal.kumaran+python at gmail.com
Tue Aug 11 13:34:35 CEST 2009


On Tue, Aug 11, 2009 at 4:52 PM, Helvin<helvinlui at gmail.com> wrote:
> 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 f.seek to move, and then rewrite, what I
> write goes to the end of the .txt file, instead of being adjusted by
> my f.seek.
>
> Do you know what way I should take?
>

It might be easier to read the file into a list of lines (using
readlines, as you do in your code already), make your change there and
write it back to a file.  If your file is indeed as small as you
indicate below, that should be significantly easier.

> Data.txt is a file of 3 lines:
>   line1
>   line2
>   line3
>
> Code:
>
>   with open('data.txt', 'r+') as f:
>       firstread = f.readlines()   # Take a snapshot of initial file
>
>       f.seek(0,0)    # Go back to beginning and search
>       for line in f:
>           print line
>           if line.find('1'):
>               print 'line matched'
>               f.seek(1,1)       # Move one space along
>               f.write('house\n')     # f.write overwrites the exact
> number of bytes.
>               break                    # leave loop once '1' is found
>
>       f.seek(0,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