[英]How to replace a specific word in specific line starting with a “keyword” python
我試圖編寫python代碼來執行以下操作,但遇到了麻煩。 請幫忙。
我有這個文件“ names.txt”
rainbow like to play football however rainbow ... etc names = rainbow, john, alex rainbow sdlsdmclscmlsmcldsc.
我需要將彩虹字替換為(已刪除)以“ name =”開頭的行
我需要代碼來搜索關鍵字“ name =”,並在同一行中將單詞“ rainbow”替換為“(已刪除)”,而無需更改其他行中的Rainbow單詞,然后用所做的更改覆蓋文件“ names.txt”像是:
rainbow like to play football however rainbow ... etc names = (Removed), john, alex rainbow sdlsdmclscmlsmcldsc.
謝謝
避免正則表達式,這是一種實現方式
with open("names.txt") as f:
content = f.readlines()
我如何將文件逐行讀入列表中進行了說明? 並且被發現使用谷歌搜索“在文件python中讀取堆棧溢出的最佳方式”。 然后獲取此內容,然后執行以下操作。
new_list_full_of_lines = [] # This is what you are going to store your corrected list with
for linea in content: # This is looping through every line
if "names =" in linea:
linea.replace ("rainbow", "(Removed)") # This corrects the line if it needs to be corrected - i.e. if the line contanes "names =" at any point
new_list_full_of_lines.append(linea) # This saves the line to the new list
with open('names.txt', 'w') as f: # This will write over the file
for item in new_list_full_of_lines: # This will loop through each line
f.write("%s\n" % item) # This will ensure that there is a line space between each line.
參考- 字符串替換似乎不起作用
其他參考- 使用Python將列表寫入文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.