[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Changing strings in files

Loris Bennett <loris.bennett at> wrote:
> Having said that, I would be interested to know what the most compact
> way of doing the same thing in Python might be.
Here's my Python replace script:-

# String replacement utility
import os
import re
import sys
import shutil

def replaceString(s1, s2, fn):
    tmpfn = "/tmp/replace.tmp"
    tofn = fn
    # copy the file to /tmp
    shutil.copy(fn, tmpfn);
    # Open the files
    fromfd = open(tmpfn, 'r');
    tofd = open(tofn, 'w');
    # copy the file back where it came from, replacing the string on the way
    for ln in fromfd:
        ln = re.sub(s1, s2, ln)

s1 = sys.argv[1]
s2 = sys.argv[2]

for fn in sys.argv[3:]:
    if (os.path.isfile(fn)):
        replaceString(s1, s2, fn)
        for srcPath, srcDirs, srcFiles in os.walk(fn):
            for f in srcFiles:
                replaceString(s1, s2, os.path.join(srcPath, f))

Chris Green