Search & Replace

Frederic Rentsch anthra.norell at vtxmail.ch
Fri Oct 27 04:32:50 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()
>
>   

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 = '''
   Left_RefAddr=FromLeft
   Left_NonRefAddr=ToLeft
   Right_RefAddr=FromRight
   Right_NonRefAddr=ToRight
'''
 >>> 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 
test data

   FromLeft=FromLeft
   ToLeft=ToLeft
   FromRight=FromRight
   ToRight=ToRight

Checks out. All substitutions are made.


Regards

Frederic





More information about the Python-list mailing list