Searching and Replacing Text in a File | python replace string in file
Youneedtochangeonestringintoanotherthroughoutafile.Stringsubstitutionismostsimplyperformedbythereplacemethodofstringobjects.Theworkhereistosupportreadingfromthespecifiedfile(orstandardinput)andwritingtothespecifiedfile(orstandardoutput):#!/usr/bin/envpythonimportos,sysnargs=len(sys.argv)ifnot3<=nargs<=5:print"usage:%ssearch_textreplace_text[infile[outfile]]"%os.path.basename(sys.argv[0])else:stext=sys.argv[1]rtext=sys.argv[2]input=sys.stdinoutput=sys.stdoutifnargs>3:input=open(sys.a...
You need to change one string into another throughout a file.
String substitution is most simply performed by the replace method of string objects. The work here is to support reading from the specified file (or standard input) and writing to the specified file (or standard output):
#!/usr/bin/env python import os, sys nargs = len(sys.argv) if not 3 <= nargs <= 5: print "usage: %s search_text replace_text [infile [outfile]]" % os.path.basename(sys.argv[0]) else: stext = sys.argv[1] rtext = sys.argv[2] input = sys.stdin output = sys.stdout if nargs > 3: input = open(sys.argv[3]) if nargs > 4: output = open(sys.argv[4], w) for s in input.xreadlines( ): output.write(s.replace(stext, rtext)) output.close( ) input.close( )This recipe is really simple, but that’s what beautiful about it—why do complicated stuff when simple stuff suffices? The recipe is a simple main script, as indicate...