Perl-Python: Find and Replace strings on Multiple Files

Xah Lee, 2005-01-30.

Here's a program that does Find and Replace on all files in a dir.

# -*- coding: utf-8 -*-
# Python

import os,sys

mydir= '/Users/t/web/mydir'

findStr='''Back to home.'''
repStr=u'''★ Back to home.'''

def replaceStringInFile(findStr,repStr,filePath):
    "replaces all findStr by repStr in file filePath"
    tempName=filePath+'~~~'
    input = open(filePath)
    output = open(tempName,'w')
  
    for s in input:
        output.write(s.replace(findStr,repStr))
    output.close()
    input.close()
    os.rename(tempName,filePath)
    print filePath

def myfun(dummy, dirr, filess):
     for child in filess:
         if '.html' == os.path.splitext(child)[1] and os.path.isfile(dirr+'/'+child):
             replaceStringInFile(findStr,repStr,dirr+'/'+child)
os.path.walk(mydir, myfun, 3)

Note that files will be overwritten. Be sure to backup the folder before you run it. Try to edit the code to suite your needs.

For a full-featured script that does find-replace in Perl, see: Find & Replace on Multiple Files with Perl


See also:


Page created: 2005-01.
© 2005 by Xah Lee.
Xah Signet