python基礎--文件操作實現全文或單行替換


python修改文件時,使用w模式會將原本的文件清空/覆蓋。可以先用讀(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 tongue
taste
taste
taste
taste
#定義一個函數,帶有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 tongue
taste
taste
taste
taste

2)全局替換

string_switch("fileread.txt","taste","tasting","g")

#結果
Yesterday when I was young
昨日當我年少輕狂
The tasting of life was sweet
生命的滋味是甜的
As rain upon my tongue
tasting
tasting
tasting
tasting

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM