[Tutor] search-replace
davidheiserca at gmail.com
davidheiserca at gmail.com
Mon Jun 6 16:26:10 CEST 2011
Or, open the file as a blob (one long string) and do a single 'replace'.
fin = open("dirtyfile.txt", 'r').read().replace('## ', '#')
open("dirtyfile.txt", 'w').write(fin)
or,
open("dirtyfile.txt", 'w').write(open("dirtyfile.txt",
'r').read().replace('## ', '#'))
----- Original Message -----
From: "Tommy Kaas" <tommy.kaas at kaasogmulvad.dk>
To: <tutor at python.org>
Sent: Monday, June 06, 2011 2:58 AM
Subject: Re: [Tutor] search-replace
> -----Oprindelig meddelelse-----
> Fra: tutor-bounces+tommy.kaas=kaasogmulvad.dk at python.org
> [mailto:tutor-bounces+tommy.kaas=kaasogmulvad.dk at python.org] På vegne
> af Alan Gauld
> Sendt: 6. juni 2011 11:51
> Til: tutor at python.org
> Emne: Re: [Tutor] search-replace
>
>
> "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)
>
Excellent! Thanks.
tommy
_______________________________________________
Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list