Replace Pattern

Christopher Koppler klapotec at chello.at
Mon Feb 9 13:59:30 CET 2004


mas at semafor.ch (Sorin Marti) wrote in message news:<6f878011.0402082345.69d74d13 at posting.google.com>...
> Hello all,
> 
> I am quite new to python and want to do the following:
> 
> - open a file (done)
> - read each line (done)
> - search a pattern in the file and replace it
> - write the new file
> 
> I want to replace the date. example: 
> INSERT INTO organization VALUES ('Brussels','Brabant','23 10 1954');
> 
> should be:
> INSERT INTO organization VALUES ('Brussels','Brabant','1954-10-24');
> 
> What i've done:
> 
> import os,sys
> try:
>         fi = open('test.sql', 'r')
>         while fi.readline():
>             line = fi.readline();
>         
> except IOError:
>         print 'Can\'t open file for reading.'
>         sys.exit(0)
> 
> Thanks for any help.

how 'bout this:

import re

pattern = r"(\d\d) (\d\d) (\d\d\d\d)"
replacement = r"\3-\2-\1"

try:
    infile = file('test.sql', 'r')
    outfile = file('new.sql', 'w')
except IOError:
    print "Can't open file."
else:
    for line in infile:
        modified = re.sub(pattern, replacement, line)
        outfile.write(modified)
    infile.close()
    outfile.close()


--
Christopher



More information about the Python-list mailing list