473,508 Members | 2,226 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Replace Pattern

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.
Jul 18 '05 #1
2 2030
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
Jul 18 '05 #2
ma*@semafor.ch (Sorin Marti) wrote in message news:<6f**************************@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
Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1641
by: William Morris | last post by:
Been pounding on this for an hour and eating up my day's productivity, so I thought I'd throw a question out there. (I'm also reading through the Google archives to try to find this answer...) ...
12
8132
by: Barnes | last post by:
Does anyone know of a good way to use the JavaScript string.replace() method in an ASP form? Here is the scenario: I have a form that cannot accept apostrophes. I want to use the replace() so...
4
10184
by: Jane Doe | last post by:
Hi, I need to search and replace patterns in web pages, but I can't find a way even after reading the ad hoc chapter in New Rider's "Inside JavaScript". Here's what I want to do: function...
22
11085
by: Phlip | last post by:
C++ers: Here's an open ended STL question. What's the smarmiest most templated way to use <string>, <algorithms> etc. to turn this: " able search baker search charlie " into this: " able...
5
11337
by: Mahesha | last post by:
Hello, I need help in replacing one string pattern with another. Ex: I have a financial security expression like log(T 3.25 6/24/2004)/sqrt(T 4.5 6/19/2002) Here "T 3.25 6/24/2004" is a...
3
8232
by: Craig Buchanan | last post by:
Is there a way to combine these two Replace into a single line? Regex.Replace(Subject, "\&", "&amp;") Regex.Replace(Subject, "\'", "&apos;") Perhaps Regex.Replace(Subject, "{\&|\'}", "{&amp;|&apos;}")...
9
4236
by: Whitless | last post by:
Okay I am ready to pull what little hair I have left out. I pass the function below my String to search, my find string (a regular expression) and my replace string (another regular expression)....
1
2783
by: Karen | last post by:
I am very new to MySQL- I currently have an VBA module using a VBSCript that will find different aspects of a text string that are a unique text string and turn it into a not so unique text string....
18
2401
by: Umesh | last post by:
Do you have any answer to it? thx.
5
2567
by: shapper | last post by:
Hello, I have a text as follows: "My email is something@something.xyz and I posted this @ 2 am" I need to replace the @ by (AT) bu only the ones that are in email addresses. All other @...
0
7225
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7326
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
7046
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7498
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5627
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5053
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4707
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3194
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
418
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.