String find and replace

hokiegal99 hokiegal99 at hotmail.com
Tue Aug 26 21:58:30 EDT 2003


I hate to answer my own post, but I think I understand what I'm doing 
wrong. I'm finding and replacing 'this' with 'that' in the varible named 
mystr, not the actual files. So, how would I go about making the change 
to the actual files instead of a variable that contains their content?

If I've got this completely wrong, someone let me know... I've been 
wrong before ;)

hokiegal99 wrote:
> Thanks for the explanation, I can make it work this way:
> 
> import os, string
> setpath = raw_input("Enter the path: ")
> for root, dirs, files in os.walk(setpath):
>    fname = files
>    x = 'THIS'
>    y = 'THAT'
>    for fname in files:
>       myfile = file(os.path.join(root,fname), 'r')
>       mystr = myfile.read()
>       myfile.close()
>       search = string.find(mystr, x)
>       if search >=1:
>          string.replace(mystr, x, y)
>          print "Replacing", x, "with", y, "in", fname
> 
> If only I could actually make the change to the files! It works in 
> theory, but not in practice ;) Anyone recommend how to actual write the 
> change to the file? I'm new to this, so be kind.
> 
> Thanks Everyone!!!





More information about the Python-list mailing list