简体   繁体   中英

Converting one column in CSV to a paragraph in html page with python

I have a code that converts CSV to HTML directly so that it looks like a table in html webpage format. However, I want it to take the first column and then convert that first column into a div with the text in the first column reading like a normal paragraph. So if:

1 5
2 6
3 7
4 8

then the div would be horizontally

1 2 3 4

5 6 7 8

so in a way i'ts some sort of transpose matrix...

The document will eventually be about 100 rows by 4 columns. I'd like to eventually pull each column and make them paragraphs after the other.

here is what the code is to turn the csv in to an html table

import sys
import csv

if len(sys.argv) < 3:
    print "Usage: csvToTable.py csv_file html_file"
    exit(1)

reader = csv.reader(open(sys.argv[1]))


htmlfile = open(sys.argv[2],"w")


colnum = 0


htmlfile.write('<div style="margin-left:220px;">')

for column in reader: 
    if colnum == 0:
        htmlfile.write('<p>') 
        for row in column:
            htmlfile.write ( row ) 
        htmlfile.write('</p>') 
    else:      
        rownum = 1
        if colnum % 2 == 0:
            htmlfile.write('<p class="color1">')
        else:
            htmlfile.write('<p class="color2">')


htmlfile.write('</div>')
exit(0)

and this is what i have reformatted in the hopes of making paragraphs

htmlfile.write('<div style=" position: absolute; margin-

left:520px; top:100px;">')

for column in reader: 
    if colnum == 0:
        htmlfile.write('<p>') 
        for row in column:
            htmlfile.write ( row ) 
        htmlfile.write('</p>') 

htmlfile.write('</div>')
exit(0)

but of course i'ts not working!! I've only been learning python for about 3 days so I don't really know how to d this yet even after pouring over books and websites

You can read the CSV file as a list of tuples using csv. reader function. Then, you can use the zip function to transpose the data. Once the rows and columns are interchanged, you can iterate through the resultant rows joining them to form a paragraph and each row as a div.

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