with open('inputFile.txt', 'r') as inp:
    with open('outfile.txt', 'w') as out:
        for line in inp:
            out.write(line.replace('blah', '!blah!'))
os.unlink('inputFile.txt')
os.rename('outfile.txt', 'inputFile.txt')
How to write before & after certain substrings in an Open file in python?