Python text search and replace text in a file

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.