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