Search & Replace

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Thu Oct 26 23:45:56 CEST 2006


In <1161898031.481159.202310 at f16g2000cwb.googlegroups.com>, DataSmash
wrote:

> I need to search and replace 4 words in a text file.
> Below is my attempt at it, but this code appends
> a copy of the text file within itself 4 times.

Because you `write()` the whole text four times to the file.  Make the 4
replacements first and rebind `text` to the string with the replacements
each time, and *then* write the result *once* to the file.

> # Search & Replace
> file = open("text.txt", "r")
> text = file.read()
> file.close()
> 
> file = open("text.txt", "w")

text = text.replace("Left_RefAddr", "FromLeft")
text = text.replace("Left_NonRefAddr", "ToLeft")
# ...
file.write(text)
file.close()

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list