简体   繁体   中英

Python HTML Table from CSV

I've been trying to read a CSV file into a HTML table through Python for a little while now. Currently my code looks like:

import csv

table = ''
with open("2016motogp.csv", encoding="utf8") as csvFile:
    reader = csv.DictReader(csvFile, delimiter=',')
    table = '<tr>{}</tr>'.format(''.join(['<td>{}</td>'.format(header) for header in reader.fieldnames]))
    for row in reader:
        table_row = '<tr>'
        for fn in reader.fieldnames:
            table_row += '<td>{}<\td>'.format(row[fn])
        table_row += '<\tr>'
        table += table_row

This is the output of the written table: https://www.w3schools.com/code/tryit.asp?filename=FG5TPW9EY3LT

It has got all the HTML table tags throughout along with a few errors in names and odd additions that shouldn't be there. The header line is clean besides the odd addition in front of the year cell.

Here is a link to the csv: https://uploadfiles.io/6joj6

If anyone could help to 'clean up' the table by adjusting the code it would be much appreciated. Thanks in advance,

EDIT: Thanks for the help, the html tags were rectified by correcting the backslash to forward-slashes, the addition to the year cell was corrected by changing the encoding option. I discovered that the \\xa0 was an encoding error or something along those lines and used: table = table.replace(u'\\xa0', u' ') to replace the additions.

Do not generate HTML "by hand", use dominate module instead. Much easier and more robust. Also, you have two typos in your code - <\\tr> should be </tr> , and <\\td> should be </td> .

As @błotosmętek already mentioned, you have <\\ instead of </ in some HTML tags.

Regarding the strange additions, it looks like the CSV is not UTF-8, it's UTF-8 with BOM . Try open("2016motogp.csv", encoding="utf-8-sig") .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM