[Tutor] Search and Replace
VanL
van@lindbergs.org
Wed, 27 Jun 2001 23:13:34 -0600
Hello,
I just did a search and replace script. It works, but I am wondering if
there is something better.
I use os.path.walk to walk through a directory tree, calling the
visitfile function on each file (quoted below).
By the way, I know that I scan through the file multiple times; I have a
version that doesn't do that, but I did it this way first to get a
little better debugging output. Just ignore that inefficiency.
def visitfile(fname, sarstrings):
stext, rtext = sarstrings[0], sarstrings[1]
matcher = re.compile(stext)
try:
if not listonly:
if os.path.splitext(fname)[1] in skipexts:
debug('Skipping: ' + fname)
elif string.find(open(fname).read(), stext) != -1:
debug('%s has %s' % (fname, stext))
linelist = open(fname, 'rb+').readlines()
file = open(fname, 'wb', 0)
for line in linelist:
line = matcher.sub(rtext, line)
file.write(line)
file.close()
fcount = fcount + 1
except: pass
Like I said, this works... but it worries me a little because I truncate
the file to 0 length and then rewrite it from the in-memory list. This
could very easily be a problem for very large files. Moreover, if the
script is interrupted, the curent file will be lost.
Is there a better way to do an in-place change?
Thanks,
Van