Search & Replace

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Thu Oct 26 18:37:11 EDT 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' 
type.

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

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)
     dest.write(line)

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)
src.close()
dest.close()
os.rename("some-temp-name.txt", "hugetext.txt")

HTH



More information about the Python-list mailing list