Posts Tagged ‘text’

Search and Replace text in files with Python

Thursday, November 29th, 2007

#!  /usr/bin/python2.5
import os

mydir = "/path/to/directory"
mysearch = "text to find"
myreplace = "Text to replace"

def doReplace(filePath):
    fin = open(filePath, "r")
    s = fin.read()
    fin.flush()
    fin.close()
    fout = open(filePath, "w")
    s = s.replace(mysearch, myreplace)
    fout.write(s)
    fout.close()

for root, dirs, files in os.walk(mydir):
    for f in files:
        name, ext = os.path.splitext(f)
        if ext == '.html':
            doReplace(root + '/' + f)

Explanation: This will find all files ending in .html in the directory specified in mydir along with all matching files in any subfolders and will replace the text specified in mysearch with the text in myreplace. It’s only been tested on Linux but with a bit of tweaking will run on Windows and Mac.