replace a line in a text file

Larry Bates lbates at swamisoft.com
Fri Jun 11 16:38:51 CEST 2004


Assumptions:

1) You wish to replace the first line that matches
(if you want to replace all, remove the ,1 in the
contents.split() function call).

2) File isn't tremendously big, if it is you should
use loop and xreadlines() to process one line at a
time.

3) There are newline characters at the end of each
of these lines (that way I can just throw away the
contents of the line and the newline character will
still be there).

Use the split function to your advantage.

linetoreplace="2.3 4.5"
f=file(filepath)
contents=f.read()
f.close()
contents="".join(contents.split(linetoreplace), 1)
f=file(filepath,'w')
f.write(contents)
f.close()

Larry Bates
Syscon, Inc.

"Luis Solís" <lsolis at mu.intecsa-inarsa.es> wrote in message
news:UWdyc.899790$A6.3514457 at telenews.teleline.es...
> I need open a text file, for example
>
> 1
> 2.3 4.5
> 4.5
>
> open file mode=x
> read the file line by line
> if some in line i == xx:
>     replace line i by newline
> close file
>
> Thanks in advance
>
>





More information about the Python-list mailing list