replace a line in a text file
peter at engcorp.com
Fri Jun 11 13:09:41 CEST 2004
Luis Solís wrote:
> I need open a text file, for example
> 2.3 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...
More information about the Python-list