[Tutor] SUPER NEWB: basic search and replace

Dave Kuhlman dkuhlman at rexx.com
Fri Sep 1 18:55:41 CEST 2006


On Fri, Sep 01, 2006 at 09:26:36AM -0700, Lanky Nibs wrote:
> I have a large volume of files to change so I need to
> automate the search and replace. I'll be replacing
> bits of text with other bits of text. This is working
> for now but I'd like to know how a real programmer
> would do it. The hard coded strings will eventually
> come from a list. All sugestions welcome and
> appreciated.
> 
>     #read all file lines into list and close
>     allLines = fh.readlines()
>     fh.close()
>     
>     #use split and join to replace a unique item
>     chunk = allLines[0]
>     splitChunk = chunk.split('xVAR1x')
>     newChunk = 'my shoes fell off'.join(splitChunk)

Instead, consider the following:

    for line in allLines:
        line = line.replace('xVAR1x', 'my shoes fell off')
        outfile.write(line)

Dave

> 
> 	#write to a file
>     file = open('test.html', 'w')
>     for eachLine in newChunk:
>     	print 'writing  line in text file'
>     	file.write(eachLine)
>     file.close()
> 

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman


More information about the Tutor mailing list