String find and replace
hokiegal99
hokiegal99 at vt.edu
Tue Aug 26 21:10:16 EDT 2003
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!!!
Geoff Gerrietts wrote:
> Quoting hokieghal99 (hokiegal99 at hotmail.com):
>
>>import os, string
>>print " "
>>setpath = raw_input("Enter the path: ")
>>def find_replace(setpath):
>> for root, dirs, files in os.walk(setpath):
>> fname = files
>> for fname in files:
>> find = string.find(file(os.path.join(root,fname), 'rb').read(), 'THIS')
>
> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> this string is never bound to a name
> (ie, you never assign str=file(...).read())
>
>> print find
>> if find >=1:
>> replace = string.replace(str, 'THIS', 'THAT')
>
> ^^^
> this name is currently bound to
> the builtin function str()
>
>
>>find_replace(setpath)
>>print " "
>
>
>
> You might consider the fragment below, instead. It's a couple lines
> longer, but safer (your .close() happens exactly when you want it to)
> and probably more readable.
>
> for root, dirs, files in os.walk(setpath):
> fname = files
> for fname in files:
> myfile = file(os.path.join(root,fname), 'rb')
> mystr = myfile.read()
> myfile.close()
> find = string.find(mystr, 'THIS')
> print find
> if find >=1:
> replace = string.replace(mystr, 'THIS', 'THAT')
>
>
> Luck,
> --G.
>
More information about the Python-list
mailing list