replace a line in a text file

Peter Hansen peter at engcorp.com
Fri Jun 11 07:09:41 EDT 2004


Luis Solís wrote:

> 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

A simple approach is

(1) open the file and read all lines from it with readlines(),
     then close it.

(2) open the file again in write mode (thus removing the
     original), then iterate over the list returned from
     readlines() doing your search/replace routine and
     writing out the lines as you go using .write(), then
     close the file.

If you need more help, I suggest posting some sample code to
show that you have made an effort to write something, or
people might suspect this is a homework assignment that you
are supposed to be figuring out for yourself...

-Peter



More information about the Python-list mailing list