When Python modifies a file, using W mode empties/overwrites the original file. You can open it in Read (R) First, write it into memory, and then open it in write (w) mode.
The taste in the replacement text is tasting
Yesterday when I am young yesterday when I was a teenager the taste of life is sweet the taste of living is sweeter as rain upon my tongue
#将文件读取到内存中with open ("./fileread.txt", "R", encoding= "Utf-8") as F:lines = F.readlines () #写的方式打开文件with Open ("./ Fileread.txt "," W ", encoding=" Utf-8 ") as F_w:for line in lines:if ' taste ' in line: #替换line = Line.replace (" Taste "," Tasting ") F_w.write (line)
2. Search replacement or single-line substitution in full text
#文本内容Yesterday When I am young yesterday I was a teenager. The Taste of life is sweet, the taste of living is as rain upon my tonguetastetastetastetaste
#定义一个函数 with 4 parameters #x represents the file name to be updated #y represents the content to be replaced #z represents the replaced content #s the default parameter is 1 to replace only the first match to the string # If the parameter is s = ' g ' Then the full text replaces the Def string_switch (x, Y, Z,s=1): With open (x, "R", encoding= "Utf-8") as f: #readlines以列表的形式将文件读出lines = F.readlines () with open (X, "W", encoding= "Utf-8") as F_w: #定义一个数字, used to record the position in the list when reading a file n = 0# default option, only replace the string in the first match to the line if s = = 1:for lines in Lines:if y : line = Line.replace (y,z) f_w.write (line) n + = 1breakf_w.write (line) n + = # to continue outputting the remaining text content for I in range (N,len (lines)): f_ W.write (Lines[i]) #全局匹配替换elif s = = ' G ': for-line in lines:if y-line:line = Line.replace (y,z) f_w.write (line)
Test
1) Default parameter 1, replaces only the first line that matches to
String_switch ("Fileread.txt", "Taste", "tasting") #结果Yesterday when I am young yesterday when I was a teenager the tasting of life was The taste of Sweet life is sweet as rain upon my tonguetastetastetastetaste
2) Global substitution
String_switch ("Fileread.txt", "Taste", "tasting", "G") #结果Yesterday when I am young yesterday when I was a teenager the tasting of life was The taste of Sweet life is sweet as rain upon my tonguetastingtastingtastingtasting