Script Discussion & Critique
mackstann
mack at incise.org
Wed Aug 27 20:22:30 EDT 2003
Looks good, there is one small bug and a couple very minor things that
basically boil down to style and personal preference.
-----------------------------------------------------------
import os # no need for string
# this can just go in one print with triple quotes
print """
******************************************************
Three Easy Steps to a Recursive find and Replace
******************************************************
"""
x = raw_input("1. Enter the string that you'd like to find: ")
# if you just want a newline, you can just do a print by itself
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 # what's this for? fname will just get reassigned on
# the next line.
for fname in files:
inputFile = file(os.path.join(root,fname), 'r')
data = inputFile.read()
inputFile.close()
search = data.find(x) # .find is a method of str, you don't need
# the string module for it.
# bug
#if search >=1: # this won't find it at the beginning of the file.
if search >= 0: # change to this (find returns -1 when it finds
# nothing)
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
# You could also do something like this to print out the centered
# messages:
print "*"*10
print "Done".center(10)
print "*"*10
-----------------------------------------------------------
HTH,
--
m a c k s t a n n mack @ incise.org http://incise.org
Dentist, n.:
A Prestidigitator who, putting metal in one's mouth, pulls
coins out of one's pockets.
-- Ambrose Bierce, "The Devil's Dictionary"
More information about the Python-list
mailing list