Python modifies file contents 3 ways

Source: Internet
Author: User

First, modify the original file method
1 def Alter (FILE,OLD_STR,NEW_STR): 2     "" "3     replaces the string in file 4     :p Aram File: File name 5     :p Aram Old_str: In the string 6     : Param new_str: New string 7     : Return:8 "" "     9     file_data =" "With     open (file," R ", encoding=" Utf-8 ") as F:11
   for line in F:12             if old_str on line:13 line                 = Line.replace (old_str,new_str)             file_data + = Line15     With open (file, "W", encoding= "Utf-8") as F:16         f.write (File_data), Alter ("File1", "09876", "Python")
Second, the original file content and the content to be modified in the new file to store the way 2.1 python string substitution method, modify the contents of the file
Import Osdef Alter (FILE,OLD_STR,NEW_STR): "" "    writes the replacement string to a new file, then deletes the original file, and the new file is changed to the original file name    :p Aram File: Path    :p Aram Old_str: string to be replaced    :p Aram New_str: Replacement string    : Return:none "" With    open (file, "R", encoding= " Utf-8 ") as F1,open ("%s.bak "% file," W ", encoding=" Utf-8 ") as F2: For line in        F1:            if old_str in line: line                = Line.replace (Old_str, New_str)            f2.write (line)    os.remove (file)    os.rename ("%s.bak"% file, file) alter ("File1", "Python", "Test")
2.2 Python replaces file contents with regular Expressions Re.sub method substitution
1 import re,os2 def alter (FILE,OLD_STR,NEW_STR): 3 4 with     open (file, "R", encoding= "Utf-8") as F1,open ("%s.bak"% file, "W", encoding= "Utf-8") as F2:5 for line in         f1:6             f2.write (re.sub (old_str,new_str,line)) 7     os.remove (file) 8     os.rename ("%s.bak"% file, file) 9 alter ("File1", "admin", "password")

Python modifies file contents 3 ways

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.