在特定匹配后替换Python中的文件内容

时间:2016-06-09 15:24:21

标签: python file-io replace

我正在尝试使用'替换'替换新条目的文件内容命令但在执行命令后截断整个数据而不是替换。请帮助。

文件:

<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()

for line in f1:
    line[line.index('<p style='color:red'><b><u>Status:</u></b>RED</p>')]='Test'

1 个答案:

答案 0 :(得分:1)

您遇到问题,因为您打开了两次相同的文件。它是这样的(至少对我而言):

with open('/var/www/html/outage/Test.html', 'r') as f1:
    text = f1.read()

text = text.replace("<p style='color:red'><b><u>Status:</u></b>RED</p>","Test")

with open('/var/www/html/outage/Test.html', 'w') as f2:
    f2.write(text)

想法是打开文件进行阅读,将内容存储在变量中,关闭它(使用with自动)。然后进行替换,再次打开文件进行写入并将修改后的内容写回来。

修改 在您提出其他问题之后:

的test.html

<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>
<li>ABC</li>
<br><b>Issue</b>:Test <br> <b>Jira:</b>
<a href=https://website.com/browse/ac-123</a>
<li>ABC</li>
<br><b>Slack:</b>

和Python代码:

with open('test.html', 'r') as f1:
    text = f1.readlines()

i = 0
while i < len(text):
        text[i] = text[i].replace("<p style='color:red'><b><u>Status:</u></b>RED</p>","Test")
        if (text[i] == '<li>ABC</li>\n'):
            text.insert(i + 1, '<li>CDF</li>\n')
            i += 1
        i +=1

with open('test1.html', 'w') as f2:
    f2.writelines(text)

请注意,这是非常有限的,只有当您知道完全行(整行,这就是为什么需要\n - 换行符号)时,才有效想要在完全匹配后插入。你当然可以根据某些东西构建字符串,但程序必须知道它们。

如果你需要更多,你应该真正研究正则表达式(Python的re模块)或真正的html解析器(我没有经验)。