Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table within an html document using python list

I have a nested list of data called new_list from a csv file in python that I need to put into a simple table in a html document.

[['Jason', 'Brown', 'Leeds', '40'], ['Sarah', 'Robinson', 'Bristol', '32'], ['Carlo', 'Baldi', 'Manchester', '41']]

I've managed to write html in the Python console for the table heading but don't know how to reference the content from the list - e.g what to put between the <tr> tags to fill in the rows. This is what I have so far:

display = open("table.html", 'w')
display.write("""<HTML>
<body>
    <h1>Attendance list</h1>
    <table>
        <tr></tr>
        <tr></tr>
    </table>
</body>
</HTML>""")

Thanks very much in advance!

like image 636
user984879 Avatar asked Sep 15 '26 13:09

user984879


1 Answers

Simple string and list manipulation.

html = """<HTML>
<body>
    <h1>Attendance list</h1>
    <table>
        {0}
    </table>
</body>
</HTML>"""

items = [['Jason', 'Brown', 'Leeds', '40'], ['Sarah', 'Robinson', 'Bristol', '32'], ['Carlo', 'Baldi', 'Manchester', '41']]
tr = "<tr>{0}</tr>"
td = "<td>{0}</td>"
subitems = [tr.format(''.join([td.format(a) for a in item])) for item in items]
# print html.format("".join(subitems)) # or write, whichever

Output:

<HTML>
<body>
    <h1>Attendance list</h1>
    <table>
        <tr><td>Jason</td><td>Brown</td><td>Leeds</td><td>40</td></tr><tr><td>Sarah</td><td>Robinson</td><td>Bristol</td><td>32</td></tr><tr><td>Carlo</td><td>Baldi</td><td>Manchester</td><td>41</td></tr>
    </table>
</body>
</HTML>

enter image description here

like image 167
NullDev Avatar answered Sep 18 '26 03:09

NullDev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!