Python Forum

Full Version: importing CSV file into a HTML table using Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to create a program which takes the values inside a CSV file and outputs them as a HTML table format. This is what i got so far. The Headers work fine it all appears as it should. But when i try to read the file it does not import the values inside it.

Here is the code, ill be happy if someone could explain why this happens
#!C:/Users/Tony/python.exe
print("content-type: text/html\n")
import csv
import html

#Create a table
print("<table>")

print("<th>")
print("<td>Student ID</td>")
print("<td>Lab+Class Activity -- Oct9 [Total Pts: 10 Score] |2336087</td>")
print("<td>OCt 10: Class Activities [Total Pts: 10 Score] |2336877</td>")
print("<td>Lab: Oct11 [Total Pts: 10 Score] |2337058</td>")
print("<td>Oct15:Class Activities [Total Pts: 10 Score] |2338422</td>")
print("<td>Oct16 [Total Pts: 10 Score] |2338579</td>")
print("<td>Class Activity Oct17 [Total Pts: 10 Score] |2339309</td>")
print("<td>Lab-Oct18 [Total Pts: 10 Score] |2339494</td>")
print("<td>Oct22, Class Activity [Total Pts: 10 Score] |2340310</td>")
print("<td>Lab-Oct23 [Total Pts: 10 Score] |2340400</td>")
print("<td>Class Activity: OCT24 [Total Pts: 10 Score] |2340833</td>")
print("<td>Lab-Oct25 [Total Pts: 10 Score] |2340970</td>")
print("<td>Final Project [Total Pts: 100 Score] |2340979</td>")
print("<td>Final Project Documentation [Total Pts: 10 Score] |2343801</td>")
print("</th>")

csv1 = open('c:/Users/Tony/File1.csv','r')

for line in csv1:
    row = line.split(",")
    a = float(row[0])
    b = float(row [1])
    c = float(row[2])
    d = float(row[3])
    e = float(row[4])
    f = float(row[5])
    g = float(row[6])
    h = float(row [7])
    i = float(row[8])
    j = float(row[9])
    k = float(row[10])
    l = float(row[11])
    m = float(row[12])
  
print("</table>")
Probably, you forgot something like this:

print("<tr>")
print("\n".join("<td>%s</td>" % v for v in row))
print("</tr>")
instead of lines 30-42.

However, I would strongly recommend to look (and use it) at some template engine (e.g. jinja2), if you want
to generate html/xml/text etc. formatted documents.