Home > OS >  Unable to add CSV information in Python for an HTML table output
Unable to add CSV information in Python for an HTML table output

Time:11-20

I am having trouble adding the data from my csv file to this html table. I'm trying to get each line displayed in the correct spot. Here's one line from my csv file as an example:

Franky Woolatt [email protected] Books $50.12 2016-12-25

This my the code I have in python currently.

import csv

table = ""
pc = ""

file1 = "XML_project.csv"
with open(file1, 'rb') as f:
contents = f.read()
table  = "<table border=1 cellpadding=1><pc><th>Date</th><th>Category</th>.  <th>Amount</th></pc>"

for line in contents:
   x = (line[0])
   date = x

   z = line[1]
   category = z

   w = line[2]
   amount = w

pc  = "<pc>"

pc  = "<td>%s</td>" % date

    
pc  = "<td>%s</td>" % category

    
pc  = "<td>%s</td>" % amount

    
pc  = "</pc>"

end = "</table>"

html = table   pc   end
files = open("results.html", 'w ')
files.write(html)
files.close() 

my output gives me this:

Date Category Amount [0] [1] [2]

Not sure what's my next step.

CodePudding user response:

I see many mistakes

  • you have wrong indentations
  • <table> doesn't have <pc> but <tr>
  • if you want read csv and get row as list of values then use csv.reader. Using f.read() or even for line in f and line[0] you should get single chars from lines
  • csv is a text file so don't open in bytes-mode rb
  • example file shows that you have date in last column but you get it from first column line[0]

I use io.String(text) only to simulate file. You should use open("XML_project.csv")

import csv
import io
text = """Franky Woolatt,[email protected],Books,$50.12,2016-12-25"""

start = "<table border=1 cellpadding=1>"

header = """
  <tr>
    <th>Date</th>
    <th>Category</th>
    <th>Amount</th>
  </tr>
"""

end = "</table>"

# ---

rows = ""

with io.StringIO(text) as f:
#with open("XML_project.csv") as f:
    cvs_readar = csv.reader(f)
    
    for line in cvs_readar:
        date = line[4]
        category= line[2]
        amount = line[3]

        rows  = f"""  <tr>
    <td>{date}</td>
    <td>{category}</td>
    <td>{amount}</td>
  </tr>
"""
      
# ---

html = start   header   rows   end

print(html)

with open("results.html", 'w ') as f:
    f.write(html)

The same with pandas

import pandas as pd

import io
text = """Franky Woolatt,[email protected],Books,$50.12,2016-12-25"""

df = pd.read_csv(io.StringIO(text), names=['Name', 'Email', 'Category', 'Amount', 'Date'])
#df = pd.read_csv("XML_project.csv", names=['Name', 'Email', 'Category', 'Amount', 'Date'])

selected = df[ ['Date', 'Category', 'Amount' ] ]
html = selected.to_html(index=False)

print(html)

selected.to_html("results.html", index=False)
  • Related