help with search & replace

Larry Bates lbates at swamisoft.com
Thu Dec 12 11:42:12 EST 2002


First, this code won't work because Python won't let you have a
variable name called if  because if is a reserved word.

I['m not entirely sure I understand what you are trying to do
but perhaps this will help.  Based on what I see I don't believe
that you need regular expressions.  Just split the lines on what
you are searching for and join them back together with what
you want to replace them with.

Try this:

infile=open(infile.txt","r")
outfile=open("outfile.txt,"w"0
for line in infile.xreadlines():
    oline=line[:]  # Get a copy of the line
    if oline.count(find_text):
        t=oline.split(find_text)      # split the line into a list on the
find_text
        oline=replace_text.join(t) # join the list back together on the
replace_text
    outfile.write(oline)

Actually if the files are not too long you can just read the entire file
using
infile.read() and use the same method.  This eliminates the loop completely
and might be written:

infile=open(infile.txt","r")
outfile=open("outfile.txt,"w"0
outfile.write(replace_text.join(f.read().split(find_text))
infile.close()
outfile.close()

Hope information helps.

-Larry

"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