HomeMathComputingArtsWordsLiteratureMusictwitter facebook webfeed

Python: Find & Replace Strings on Multiple Files

Advertise Here For Profit

Xah Lee, 2005-01-30, 2011-02-08

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.

See also: Perl: Find & Replace on Multiple Files.

blog comments powered by Disqus