[Tutor] SUPER NEWB: basic search and replace

Kent Johnson kent37 at tds.net
Fri Sep 1 18:53:51 CEST 2006


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]
>   
Is the data to be replaced always in the first line? You only look at 
the first line.
>     splitChunk = chunk.split('xVAR1x')
>     newChunk = 'my shoes fell off'.join(splitChunk)
>   
This is a very awkward way to replace part of a string. Try
newChunk = chunk.replace('xVAR1x', 'my shoes fell off')
> 	#write to a file
>     file = open('test.html', 'w')
>     for eachLine in newChunk:
>     	print 'writing  line in text file'
>     	file.write(eachLine)
>     file.close()
>   
Are you sure this is doing what you want? newChunk is just the first 
line of the file, iterating over it gives you each character from the file.

If I wanted to replace every instance of 'xVAR1x' in a single file with 
'my shoes fell off', I would do it like this:

f = open(...)
data = f.read()
f.close()

data = data.replace('xVAR1x', 'my shoes fell off')

f = open(..., 'w')
f.write(data)
f.close()

Variations are possible depending on exactly what you want to do, but 
this is the basic idea. No need to read a line at a time unless you 
actually need to process by lines, or if the file is too big to fit in 
memory (in which case your solution still needs a rewrite).

Kent
>
> __________________________________________________
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around 
> http://mail.yahoo.com 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   




More information about the Tutor mailing list