python修改文件時(shí),使用w模式會(huì)將原本的文件清空/覆蓋。可以先用讀(r)的方式打開,寫到內(nèi)存中,然后再用寫(w)的方式打開。
1、替換文本中的taste 為 tasting
Yesterday when I was young昨日當(dāng)我年少輕狂The taste of life was sweet生命的滋味是甜的As rain upon my tongue
#將文件讀取到內(nèi)存中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、全文中搜索替換或者單行替換
#文本內(nèi)容Yesterday when I was young昨日當(dāng)我年少輕狂The taste of life was sweet生命的滋味是甜的As rain upon my tonguetastetastetastetaste
#定義一個(gè)函數(shù),帶有4個(gè)參數(shù)#x 表示要更新的文件名稱#y 表示要被替換的內(nèi)容#z 表示 替換后的內(nèi)容#s 默認(rèn)參數(shù)為 1 表示只替換第一個(gè)匹配到的字符串# 如果參數(shù)為 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: #定義一個(gè)數(shù)字,用來(lái)記錄在讀取文件時(shí)在列表中的位置 n = 0 #默認(rèn)選項(xiàng),只替換第一次匹配到的行中的字符串 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 #將剩余的文本內(nèi)容繼續(xù)輸出 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)
測(cè)試
1)默認(rèn)參數(shù) 1,只替換匹配到的第一行
string_switch("fileread.txt","taste","tasting") #結(jié)果Yesterday when I was young昨日當(dāng)我年少輕狂The tasting of life was sweet生命的滋味是甜的As rain upon my tonguetastetastetastetaste2)全局替換
string_switch("fileread.txt","taste","tasting","g") #結(jié)果Yesterday when I was young昨日當(dāng)我年少輕狂The tasting of life was sweet生命的滋味是甜的As rain upon my tonguetastingtastingtastingtasting以上這篇python基礎(chǔ)_文件操作實(shí)現(xiàn)全文或單行替換的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選