Search and replace of text in files via external tools

Last edited on

The following is a simple implementation of a command line tool for performing search & replace operations in files.

Be aware that it performs this operation by loading the complete file into memory, and then writing it to the output file. This can be a lengthy operation, depending on file size and memory of the respective computer.

import codecs
import os
import sys

def replace_in_file( input_file, output_file, search_for, replace_with ):
    data = read_file_utf8( input_file )
    data = data.replace( search_for, replace_with )
    write_file_utf8( output_file, data )

def read_file_utf8( file_name ):
    f = file_name, "r", "utf8" )
    res =
    return res

def write_file_utf8( file_name, content ):
    f = file_name, "w", "utf8" )
    f.write( content )

if __name__ == "__main__":
    if len( sys.argv ) != 5:
        print "USAGE: %s input_file output_file search_for replace_with" % (sys.argv[0])
        replace_in_file( sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4] )
python test.template.txt test.txt c:\suite_test\ \\\c:\suite_test\
Usage in cmd.exe