[SOLVED] Output pretty table to an html file?

Issue

This Content is from Stack Overflow. Question asked by Java_Assembly55

I can’t seem to get a clear cut answer on how to do this. I have a pretty table that I print to the terminal but what if I want to create an html file and print the table to that html file? How can this be done.

This is my table that I have, how could I go about writing this to a new html file?

        tbl = PrettyTable(["Occurs", "Occurrences"])
        for word, cnt in matches.items():
            tbl.add_row([word, cnt])
        tbl.align = 'l'
        print(tbl.get_string(sortby="Occurrences", reversesort=True))



Solution

You have the get_html_string (doc on the github readme) which will allow you to have the html and then you write the string into a html file like this:

from pathlib import Path
tbl = PrettyTable(["Occurs", "Occurrences"])
for word, cnt in matches.items():
    tbl.add_row([word, cnt])
tbl.align = 'l'
to_save = tbl.get_html_string(sortby="Occurrences", reversesort=True)
with Path("my_html_file.html").open(mode="w", encoding="utf-8") as fp:
    fp.write(to_save)


This Question was asked in StackOverflow by Java_Assembly55 and Answered by ndclt It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?