Search & Replace

Bruno Desthuilliers bdesth.quelquechose at
Fri Oct 27 00:37:11 CEST 2006

DataSmash a écrit :
> 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")
NB : avoid using 'file' as an identifier - it shadows the builtin 'file' 

> text =
> 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()

See Mark and Tim's answers for your bug. Another (potential) problem 
with your code is that it may not work too well for big files. It's ok 
if you know that the files content will always be small enough to not 
eat all memory. Else, taking a "line by line" approach is the canonical 
solution :

def simplesed(src, dest, *replacements):
   for line in src:
     for target, repl in replacements:
       line = line.replace(target, repl)

replacements = [
   ("Left_RefAddr", "FromLeft"),
   ("Left_NonRefAddr", "ToLeft"),
   ("Right_RefAddr", "FromRight"),
   ("Right_NonRefAddr", "ToRight"),
src = open("hugetext.txt", "r")
dest = open("some-temp-name.txt", "w")
simplesed(src, dest, *replacements)
os.rename("some-temp-name.txt", "hugetext.txt")


More information about the Python-list mailing list