1 #! /usr/local/env python2 ImportOS, sys3Nargs =Len (SYS.ARGV)4 if not3 <= Nargs <= 5:5 Print "Usage:%s search_text replace_text [Inputfiel [outputfile]]"%Os.path.basename (sys.argv[0]) #友好交互性提示6 Else :7Stext = sys.argv[1] #获取当前环境参数 is the $search_text8Rtext = sys.argv[2] #同上9 ifNargs > 3:TenInput_file = open (sys.argv[3]) One ifNargs > 5: Aoutput_file = open (Sys.argv[4],'W') - forSinchInput_file: - Output_file.write (S.replace (stext, rtext))
input_file.close ()
Since my first execution of the shell command line in the Python GUI under Windows has always prompted Syntaxerror:invalid syntax's error, it was later discovered that there was a problem with the execution environment.
The main implementation function is: The text content Serach_text replaced with replace_text content, if there is an input and output file, the Search_text content in Inputfile is replaced with replace_text content, and output it to the OutputFile file.
Share with us!
Python text search and replace text in a file