Python to make html tables code

I think that to make a table in html is really boring. So I thought it could be nice to use Python to avoid having to write all those html tags.

The simpliest table in the world would be like this:

<table border=1>
<tr><td>Name</td><td>Surname</td><td>Age</td></tr>
<tr><td>John</td><td>Marr</td><td>18</td></tr>
<tr><td>Marion</td><td>Sally</td><td>28</td></tr>
</table>

This is it:

Name Surname Age
John Marr 18
Marion Sally 28

Using Python to do the boring stuffs

Imagine having to do more complex tables. So, here is the code to avoid all this.

First, we write the data in this simple way

data = """

        Name,    Surname,    Age
        John,    Smith,      18
        Mary,    Luise,      24
             
"""

Then we split the lines and delete the empty ones, adding also the tr and some td tags.

data = data.splitlines()
data = [d.strip() for d in data]
data = [f"<tr><td>{d}</tr>" for d in data if d.strip() != ""]

Then we let python add the table tag at the end and the beginnig

data = "<table border=1>" + "".join(data) + "</table>"

We replace the commas with something useful (the rest of the tags we need)

data = data.replace(",","</td><td>")

And we save our code in an html file, we’re done

with open("table.html", "w", encoding="utf-8") as file:
    file.write(data)

The final output

The entire code

This is the whole code (made in jupyter lab, so you’ll find something more, watch the video to understand why there are those other lines of code).

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from IPython.display import display, HTML

import os

data = """

        Name,    Surname,    Age
        John,    Smith,      18
        Mary,    Luise,      24
             
"""
data = data.splitlines()
data = [d.strip() for d in data]
data = [f"<tr><td>{d}</tr>" for d in data if d.strip() != ""]
data = "<table border=1>" + "".join(data) + "</table>"
#display(HTML(data))
data = data.replace("    ","")
data = data.replace(",","</td><td>")
data
# Comment this if you don't use jupyter
display(HTML(data))
with open("table.html", "w", encoding="utf-8") as file:
    file.write(data)
os.startfile("table.html")

The video about making an html table with Python

The code without the jupyter lab commands

import os

data = """

        Name,    Surname,    Age
        John,    Smith,      18
        Mary,    Luise,      24
             
"""
data = data.splitlines()
data = [d.strip() for d in data]
data = [f"<tr><td>{d}</tr>" for d in data if d.strip() != ""]
data = "<table border=1>" + "".join(data) + "</table>"
data = data.replace("    ","")
data = data.replace(",","</td><td>")
with open("table.html", "w", encoding="utf-8") as file:
    file.write(data)
os.startfile("table.html")

 

 

Another way to do it

This code was a little different, but the output is the same.

import os



def savehtml(filename="defaulthtml"):
    htmldata = data2list(data)
    htmldata = htmldata.replace("<table>", f"<table border={border}")
    with open("Simple.html", "w", encoding="utf-8") as filehtml:
        filehtml.write(htmldata)
    os.startfile("Simple.html")

def data2list(data):
    d = data.splitlines()[1:-1]
    d = [x.split(",") for x in d]
    for row in d:
        for e in row:
            e_index = row.index(e)
            cell = "<td>" + e.strip() + "</td>"
            if e_index == 0:
                d[d.index(row)][row.index(e)] = "<tr>" + cell
            elif e_index == len(row) -1:
                d[d.index(row)][row.index(e)] = cell + "</tr>"
            else:
                d[d.index(row)][e_index] = cell
    d = [i for sublist in d for i in sublist]
    return "<table>" + "".join(d) + "</table>"
 
 
# ============== Persolized data ================
border = 1
data = """
Impiegato,      Performance,    data
Rossi Mario,    1000,           1/2/2018
Baldo Franco,   2000,           1/2/2018
    """
savehtml(filename="Simple.html")

 

Other posts about the same topic

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.