简体   繁体   中英

Replace file contents in Python after specific match

I am trying to replace file contents with new entry using 'replace' command but after execution command is truncating whole data in place of replace.Please help.

File:

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

Replace script:

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'

You have a problem because you open the same file twice. It works like this (at least for me):

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)

The idea is to open the file for reading, store the content in a variable, close it (automatic with with ). Then do the replacement, open the file again for writing and write the modified content back.

EDIT: After you additional question:

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>

and the Python code:

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)

Note that this is very limited and only works if you know the exact line (the whole line, that's why the \\n -line break is required) that you want to insert after the exact match. You can of course build the strings depending on something, but the program has to know them.

If you need any more than this you should really look into regular expressions (the re module of Python) or a real html-parser (which I have no experience with).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM