Python: Find/Replace Strings on Multiple Files

By Xah Lee. Date: . Last updated: .
python science find replace 2017 03 12
python science

Here's a example Python script that does Find and Replace on all files in a dir.

# -*- coding: utf-8 -*-
# python

# example of find/replace for all html files in a dir
# warning: this example does not deal with Unicode encoded files well

import os, sys, shutil

inputDir = "/home/jane/web/"

findStr = r"""Insects"""
repStr = r"""Ants"""

def replaceStringInFile(findStr, repStr, filePath):
    "replaces all findStr by repStr in file filePath"
    tempName = filePath+'~~'
    backupName = filePath+'~'
    inputFile = open(filePath)
    outputFile = open(tempName, 'w')

    for thisLine in inputFile:
        outputFile.write(thisLine.replace(findStr, repStr))

    shutil.copy2(filePath, backupName)
    os.rename(tempName, filePath)
    print "file processed: {}".format(filePath)

def filterFile(dummyArg, thisDir, dirChildrenList):
     for thisChild in dirChildrenList:
         if '.html' == os.path.splitext(thisChild)[1] and os.path.isfile(thisDir+'/'+thisChild):
             replaceStringInFile(findStr, repStr, thisDir+'/'+thisChild)

os.path.walk(inputDir, filterFile, None)

If you have a question, put $5 at patreon and message me.