Python remove or replace a certain part in several text files

 Sometimes you need to remove or replace a certain part in several text files and if that is 20 or 100 or completely 1000 templates that is a whole load of work. How can you do it with python? That goes without saying that it's a weird case and normally you only have 1 or 2 template files but imagine if you have a static static generator and no CMS then you may occasionally find yourself in a situation where you will need such a script. To avoid such situations, keep content separate from tempaltes.

NOTE: commit and test how it works first without opening file to write. 


 You can see correct representation of text in debugger and copy there.

Python replace long string 

python replace multiline string in file

import glob
import sys, os
import re

def replace(content):
    replace = '<section class="grey-bg" id="why-dessiner">\n\t\t<div class="content content-width" id="why-content">\n\t\t\t<h2>Meer informatie?</h2>\n\t\t\t<div class="features">\n{% include \'include/left.html\' %}\n{% include \'include/center.html\' %}\n{% include \'include/right.html\' %}\n            </div>\n    </div>\n\t</section>'
    content = content.replace(replace, "")
    return content

def main(argv):
    inputfiles = glob.glob("input/*.html")
    for infile in inputfiles:
        head, tail = os.path.split(infile)
        print("----- In file ------")
        print(infile)
        content = open(infile, "r").read()
        content = replace(content)
        print(content)
        #outfile = open(infile, "w")
        content = content.encode('utf-8')
        content = content.decode('utf-8')
        #outfile.write(content)
        #outfile.close()

Comments