Search code examples
pythonhtmlprettytable

Output pretty table to an html file?


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)