Search & Replace
anthra.norell at vtxmail.ch
Fri Oct 27 04:32:50 EDT 2006
> 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.
> # Search & Replace
> file = open("text.txt", "r")
> text = file.read()
> 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"))
Here's a perfect problem for a stream editor, like
http://cheeseshop.python.org/pypi/SE/2.2%20beta. This is how it works:
>>> replacement_definitions = '''
>>> import SE
>>> Replacements = SE.SE (replacement_definitions)
>>> Replacements ('text.txt', 'new_text.txt')
That's all! Or in place:
>>> ALLOW_IN_PLACE = 3
>>> Replacements.set (file_handling_flag = ALLOW_IN_PLACE)
>>> Replacements ('text.txt')
This should solve your task.
An SE object takes strings too, which is required for line-by-line
processing and is very useful for development or verification:
>>> print Replacements (replacement_definitions) # Use definitions as
Checks out. All substitutions are made.
More information about the Python-list