help with search & replace

Bill Blue billblue at cham.com
Thu Dec 12 09:46:43 EST 2002


I have a text file that has numbers is many places thru out the file
ie "20:22:12" .  I need to be able to create a new file and make
changes only to those numbers above.  I used this to find them

import re,string,sys

if = open("infile.txt","r")
of = open("outfile.txt,"w")
for line in if.xreadlines():
	fs = re.compile(r"\d+:\d+:\d+").findall(line)  # there may be
more than one in a line.
	if fs:
		for num in fs:
			of.write(lne.replace(num,num[0:5]+"00")) # the
replace text is not always the same
	else:
		of.write(line)  # for line where no match is found

The above works if there is only 1 match or number on a line, if there
are more that one then I get multiple lines in the output file.   in
most cases there may be 3-6 matches on one line.

input line is:
another time  01:12:36 the normal time for these is  01:12:45

here is the busted output:

>another time  01:12:00 the normal time for these is  01:12:45  
>another time  01:12:36  the normal time for these is  01:12:00 

I would like to be able to replace all occurences in one line with out
generating multiple output lines.


 Any help on this wold be appreciated.

Bill B.




More information about the Python-list mailing list