我試圖用'替換'命令替換文件內容,但執行後命令截斷整個數據替換replace.Please幫助。特定匹配後用Python替換文件內容
文件:
<b><center><u>S0 Outage Communication</u></center></b>
<br><br> <b>Date</b>:08/June/2016 <br> <br> <strong>Time</strong>:01:49 <br>
<p style='color:red'><b><u>Status:</u></b>RED</p>
<br><b>Issue</b>:Test <br> <b>Jira:</b>
<a href=https://website.com/browse/ac-123</a>
<br><b>Slack:</b>
替換腳本:
f1 = open('/var/www/html/outage/Test.html', 'r')
f2 = open('/var/www/html/outage/Test.html', 'w')
for line in f1:
f2.write(line.replace("<p style='color:red'><b><u>Status:</u></b>RED</p>","Test"))
f1.close()
f2.close()
OR
for line in f1:
line[line.index('<p style='color:red'><b><u>Status:</u></b>RED</p>')]='Test'
您需要打開第二個文件,然後將每一行寫入您想要更改的行。然後寫入已更改的行,並繼續將輸入文件中剩餘的行寫入輸出文件。最後,您可以刪除舊文件或重命名它,並將新文件重命名爲原始文件名 –