This article mainly introduces the Python basic _ file operation to achieve full-text or single-line replacement method, has a certain reference value, now share to everyone, the need for friends can refer to
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.
1. 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 "on line: #替换 line = Line.replace (" t Aste "," 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 the file is read n = 0 #默认选项, replace only the string in the first match to the line if s = = 1: For the lines: if y in line: line = Line.replace (y,z) f_w.write (line) n + = 1 break f_ W.write (line) n + = 1 #将剩余的文本内容继续输出 for i in range (N,len (lines)): f_w.write (Lines[i]) # Global match Replace elif s = = ' G ': for-line in lines: If-y in 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