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 = codecs.open( file_name, "r", "utf8" )
res = f.read()
f.close()
return res
def write_file_utf8( file_name, content ):
f = codecs.open( file_name, "w", "utf8" )
f.write( content )
f.close()
if __name__ == "__main__":
if len( sys.argv ) != 5:
print "USAGE: %s input_file output_file search_for replace_with" % (sys.argv[0])
else:
replace_in_file( sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4] )
python search_and_replace_all.py test.template.txt test.txt c:\suite_test\ \\10.24.0.41\c:\suite_test\