[Tutor] search-replace

Alan Gauld alan.gauld at btinternet.com
Mon Jun 6 11:51:22 CEST 2011


"Tommy Kaas" <tommy.kaas at kaasogmulvad.dk> wrote


> I'm especially interested to know how I do more than just one 
> search-replace
> without having to repeat the whole step below.
> fin = open("dirtyfile.txt")
> fout = open("cleanfile.txt", "w")
> for line in fin:
>    fout.write(line.replace('## ', '#'))
> fin.close()
> fout.close()

Can be simplified to:

with open("cleanfile.txt", "w") as fout:
     for line in open("dirtyfile.txt"):
           fout.write(line.replace('## ', '#'))

To do multiple replaces simply expand the inner block


     for line in open("dirtyfile.txt"):
           line = line.replace(....)   #first
           line = line.replace(....)   #second etc
           fout.write(line)

Or if you have a lot of them:

replacePatterns = [('##','#'),('!!!','!!'),....]

     for line in open("dirtyfile.txt"):
            for old,new in repace_patterns:
                 line = line.replace(old,new)
            fout.write(line)

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list