help with search & replace

Lei Chen llchen223 at hotmail.com
Thu Dec 12 17:17:26 EST 2002


Hello,

This will solve your problem:


1 inFile = open("infile.txt","r")
2 of = open("outfile.txt","w")
3 for line in inFile.xreadlines():
4     fs = re.compile(r"(\d+:\d+:\d+)").findall(line)
5     if fs:
6         for num in fs:
7             line = line.replace(num,num[0:6]+"00")
8         of.write(line)
9     else:
10        of.write(line)  # for line where no match is found



Changes are on line 7 and 8.

Bill Blue <billblue at cham.com> wrote in message news:<7u6hvu8as4laud5jpp9qapi2kopj1dlsif at 4ax.com>...
> 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