Skip to content Skip to sidebar Skip to footer

Python: Writing Html Anchor Points Dynamically Based On Number Of String Finds

So the intention of my script is to take in a log file, highlight any lines that contain the word 'ERROR', and then create and open a HTML file for displaying the log with the form

Solution 1:

  • This is because you are using last error link created by previous loop.
  • For second loop where you are adding <span> tag you need to start count from zero again.
  • try this code it should work.
infile = r"/Users/username/test-full-log.log"

with open(infile) as f:
    f = f.read()
    error_occurances = f.count("ERROR")

with open(infile, 'r') as IN, open('output.html', 'w') as OUT:
    for x in range(error_occurances):
        error_links = "example" + str(x)
        OUT.write('<a href=' + '"' + '#' + error_links + '"' '>' + error_links + '</a>' + "\t")
    OUT.write("<pre>")
    x = 0
    for line in IN:
        if "ERROR" in line:
            error_links = "example" + str(x)
            x+=1
            f = '<a id=' + '"' + error_links + '"' '></a><span style="background-color: #ff0000; color: #ffffff;">' + line + '</span>'
            OUT.write(f + '\n')
        else:
            OUT.write(line + '\n')
    OUT.write("</pre")

Post a Comment for "Python: Writing Html Anchor Points Dynamically Based On Number Of String Finds"