user984879
user984879

Reputation: 51

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!

Upvotes: 2

Views: 13080

Answers (6)

Claire McWhite
Claire McWhite

Reputation: 1

Late answer, but converting to a Pandas DataFrame then using the pandas to_html function is a quick way to get to html tables without string formatting.

new_list = [['Jason', 'Brown', 'Leeds', '40'], ['Sarah', 'Robinson', 'Bristol', '32'], ['Carlo', 'Baldi', 'Manchester', '41']]
df = pd.DataFrame(newlist)
html = df.to_html(classes = 'Attendance', index=False, header=False)
>>> print(html)
<table border="1" class="dataframe Attendance">
  <tbody>
    <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>
  </tbody>
</table>

Upvotes: 0

alecxe
alecxe

Reputation: 473853

The right tool for the job is a Template Engine. You clearly have an HTML template and the data you want to be appropriately inserted into the HTML in the specified placeholders.

Example using mako:

In [1]: from mako.template import Template
In [2]: rows = [['Jason', 'Brown', 'Leeds', '40'], ['Sarah', 'Robinson', 'Bristol', '32'], ['Carlo', 'Baldi', 'Manchester', '41']]
In [3]: template = """
        <html>
            <body>
                <table>
                     % for row in rows:
                     <tr>
                          % for cell in row:
                          <td>${cell}</td>
                          % endfor
                     </tr>
                     % endfor
                </table>
            </body>
        </html>"""

In [4]: print(Template(template).render(rows=rows))
<html>
    <body>
        <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>

Isn't it simple and readable? And, as a bonus, no direct and manual HTML string manipulation.

Upvotes: 3

Dror Hilman
Dror Hilman

Reputation: 7447

I would do something like that...

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

#First, create the texts of the columns:
cols = ["<td>{0}</td>". format( "</td><td>".join(t)  ) for t in tbl]

#then use it to join the rows (tr)
rows = "<tr>{0}</tr>".format( "</tr>\n<tr>".join(cols) )

#finaly, inject it into the html...
display = open("table.html", 'w')
display.write("""<HTML> <body>
                           <h1>Attendance list</h1>
                            <table>  
                              {0}  
                            </table>
                        </body>  
                  </HTML>""".format(rows))

This will result in :

<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>

Upvotes: 1

WGS
WGS

Reputation: 14169

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

Upvotes: 5

G&#225;bor Erdős
G&#225;bor Erdős

Reputation: 3689

This should do the trick

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

result_string = """<HTML>
<body>
    <h1>Attendance list</h1>
    <table>\n"""
for i in new_list:
    result_string += "        <tr>\n            "
    for j in i:
        result_string += "<td>%s</td>" %j
    result_string += "\n        </tr>\n"
result_string += """    </table>
</body>
</HTML>"""
display = open("table.html", 'w')
display.write(result_string)
display.close()

Upvotes: 0

Michał Fita
Michał Fita

Reputation: 1319

I think good start for you is string formatting available from build-in Python module. If you need it for lower Python version, it hasn't change much since 2.5.

Usually web/html stuff is handled by some more sophisticated web framework, like Django or TurboGears, but this may not be your use case.

Upvotes: 1

Related Questions