Search & Replace

Paddy paddy3118 at netscape.net
Fri Oct 27 00:19:58 EDT 2006


DataSmash wrote:
> Hello,
> 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.
> Can someone help me out.
> Thanks!
>
> # Search & Replace
> file = open("text.txt", "r")
> text = file.read()
> file.close()
>
> 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()

Check out the Pythons standard fileinput module. It also has options
for in-place editing.

(
http://groups.google.com/group/comp.lang.python/msg/2d88c0f5e17f004e?hl=en&
)

- Pad.




More information about the Python-list mailing list