replace a line in a text file

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


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

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"
contents="".join(contents.split(linetoreplace), 1)

Larry Bates
Syscon, Inc.

"Luis Solís" <lsolis at> wrote in message
news:UWdyc.899790$A6.3514457 at
> 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