String find and replace

hokiegal99 hokiegal99 at hotmail.com
Wed Aug 27 12:41:24 EDT 2003


Thomas Güttler wrote:
> I once wrote a replace recursive script. Maybe it helps you:
>  http://www.thomas-guettler.de/scripts/replace-recursive.py.txt
> 
> thomas

Yes that's very helpful, but a bit too complex for me at this point in 
time. Here is the script that I put together from all of the responses I 
recieved from the list:

#Thanks to comp.lang.python
import os, string
print " "
print "******************************************************"
print "   Three Easy Steps to a Recursive find and Replace   "
print "******************************************************"
print " "
x = raw_input("1. Enter the string that you'd like to find: ")
print " "
y = raw_input("2. What would you like to replace %s with: " %x)
print " "
setpath = raw_input("3. Enter the path where the prgroam should run: ")
print " "
for root, dirs, files in os.walk(setpath):
    fname = files
    for fname in files:
       inputFile = file(os.path.join(root,fname), 'r')
       data = inputFile.read()
       inputFile.close()
       search = string.find(data, x)
       if search >=1:
          data = data.replace(x, y)
          outputFile = file(os.path.join(root,fname), 'w')
          outputFile.write(data)
          outputFile.close()
          print "Replacing", x, "with", y, "in", fname
print " "
print "**********"
print "   Done   "
print "**********"
print " "





More information about the Python-list mailing list