Search & Replace

Tim Chase python.list at
Thu Oct 26 23:54:34 CEST 2006

> Below is my attempt at it, but this code appends
> a copy of the text file within itself 4 times.
> Can someone help me out.
> file = open("text.txt", "w")
> file.write(text.replace("Left_RefAddr", "FromLeft"))
> file.write(text.replace("Left_NonRefAddr", "ToLeft"))
> file.write(text.replace("Right_RefAddr", "FromRight"))
> file.write(text.replace("Right_NonRefAddr", "ToRight"))
> file.close()

Well, as you can see, you're writing (write()) the text 4 times.

Looks like you want something like

"FromRight").replace("Right_NonRefAddr", "ToRight"))

which is about the equiv. of

text = text.replace(...1...)
text = text.replace(...2...)
text = text.replace(...3...)
text = text.replace(...4...)

I would also be remiss if I didn't mention that it's generally 
considered bad form to use the variable-name "file", as it 
shadows the builtin "file".

There are additional ways if replacements cause problems that 
then themselves get replaced, and this is an undesired behavior. 
  However, it looks like your example doesn't have this problem, 
so the matter is moot.


More information about the Python-list mailing list