HomeMathComputingArtsWordsLiteratureMusictwitter facebook webfeed

Python: Find & Replace Multi-line Strings in a Dir

Advertise Here For Profit

Xah Lee, 2005-02-03, 2011-02-08

Previously we wrote a script that does find & replace of a string for all files in a dir. (See: Python: Find & Replace Strings on Multiple Files.)

Now suppose in your html file, you want to replace the text:

<body>

<table>

by this text:

<body>
<h1>New Pricing!</h1>
<table>

The find text has multiple lines. So, our old code won't work because it process one line at a time. One solution is to read the file content all at once as a string. Here's the solution:

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

import os,sys

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

findStr='''<body>

<table>'''
repStr='''<body>\n<P>new stuff!</p>\n<table>'''


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

   s=input.read()
   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)

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

blog comments powered by Disqus