Changing strings in files

Chris Green cl at isbd.net
Tue Nov 10 03:25:59 EST 2020


Loris Bennett <loris.bennett at fu-berlin.de> 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:-


#!/usr/bin/python3
#
#
# 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)
        tofd.write(ln)
    tofd.close()

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

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

-- 
Chris Green
·


More information about the Python-list mailing list