Replace Pattern

Peter Otten __peter__ at web.de
Mon Feb 9 05:17:31 EST 2004


Sorin Marti wrote:

> 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');
> 

I'm assuming the 24 is a typo, and that you want to change the date format
from 'DD MM YYYY' to 'YYYY-MM-DD'. Otherwise use 

line.replace("23 10 1954", "1954-10-24")

There must be simpler ways, but this is what I did:

import re

r = re.compile(r"\'(\d\d) (\d\d) (\d\d\d\d)'")

def adjustDate(m):
    return "'%s-%s-%s'" % (m.group(3), m.group(2), m.group(1))

infile = file("in.sql")
outfile = file("out.sql", "w")
for line in infile:
    outfile.write(r.sub(adjustDate, line))

The type of search pattern used is called regular expression, and if you
want to understand them, A. M. Kuchling has written a nice Howto for Python
users.

> 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.'

That's the most probable error, but you cannot be sure. In those rare cases
when a problem occurs in the while loop, you are misleading the user -
which could well be yourself :-)
While it's good to start with proper error handling as early as possible, in
the case of a small conversion script, a traceback printed by an uncaught
exception could even be more helpful.

>         sys.exit(0)

Why would you want to exit your script with 0 (indicating success) if and
error occured?


Peter



More information about the Python-list mailing list