python修改文件時,使用w模式會將原本的文件清空/覆蓋??梢韵扔米x(r)的方式打開,寫到內存中,然后再用寫(w)的方式打開。
1、替換文本中的taste 為 tasting
Yesterday when I was young昨日當我年少輕狂The taste of life was sweet生命的滋味是甜的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、全文中搜索替換或者單行替換
#文本內容Yesterday when I was young昨日當我年少輕狂The taste of life was sweet生命的滋味是甜的As rain upon my tonguetastetastetastetaste
#定義一個函數,帶有4個參數#x 表示要更新的文件名稱#y 表示要被替換的內容#z 表示 替換后的內容#s 默認參數為 1 表示只替換第一個匹配到的字符串# 如果參數為 s = 'g' 則表示全文替換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: #定義一個數字,用來記錄在讀取文件時在列表中的位置 n = 0 #默認選項,只替換第一次匹配到的行中的字符串 if s == 1: for line in 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]) #全局匹配替換 elif s == 'g': for line in lines: if y in line: line = line.replace(y,z) f_w.write(line)
測試
1)默認參數 1,只替換匹配到的第一行
string_switch("fileread.txt","taste","tasting") #結果Yesterday when I was young昨日當我年少輕狂The tasting of life was sweet生命的滋味是甜的As rain upon my tonguetastetastetastetaste2)全局替換
string_switch("fileread.txt","taste","tasting","g") #結果Yesterday when I was young昨日當我年少輕狂The tasting of life was sweet生命的滋味是甜的As rain upon my tonguetastingtastingtastingtasting以上這篇python基礎_文件操作實現全文或單行替換的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答