CSV to HTML Table with Python
Project Overview:
This purpose of this project is to write the contents of a csv file to an html file in the form of a table. The first row of the csv file is assumed to be a header row. The table will have predefined css styles applied to it. The styles will customize the header as well as alternate the color of each row.
Description of Code:
Starting on line 9, this if statement tests the number of arguments and and terminates the application with an exit status of 1 if the number of arguments are less than 3. Line 14 makes use of the csv modules reader object and loads the contents of the specified csv file into a variable “reader”. Line 17, creates an html file with the name specified in the second argument and opens it for writing. Line 23 simply writes the opening html table tag. Line 25 enters a for loop where each row of the csv file is read and written to the html file appropriately. Lines 26 though 30 write the header row. Lines 32 through 36 apply the css classes color1 and color2 to alternating rows. This allows the external css to alternate colors to make the each row of the table more readable to the end user.Lines 38 through 41 write the columns in the table. Additionally, they write the number of the columns position in the table. This allows external css to apply unique styling to each column. Line 46 ends the html table tag and Line 47 terminates the script with an exit status of 0.
The Code:
#!/usr/bin/python # create html table from csv # Author(s): Chris Trombley <ctroms@gmail.com> # Version 2 - added css class to all columns except header import sys import csv if len(sys.argv) < 3: print "Usage: csvToTable.py csv_file html_file" exit(1) # Open the CSV file for reading reader = csv.reader(open(sys.argv[1])) # Create the HTML file for output htmlfile = open(sys.argv[2],"w") # initialize rownum variable rownum = 0 # write <table> tag htmlfile.write('<table>') for row in reader: # Read a single row from the CSV file if rownum == 0: htmlfile.write('<tr>') # write <tr> tag for column in row: htmlfile.write('<th>' + column + '</th>') # write header columns htmlfile.write('</tr>') # write </tr> tag else: # write all other rows colnum = 1 if rownum % 2 == 0: htmlfile.write('<tr class="color1">') else: htmlfile.write('<tr class="color2">') for column in row: htmlfile.write('<td class="column_' + str(colnum) + '">' + column + '</td>') colnum += 1 htmlfile.write('</tr>') rownum += 1 # write </table> tag htmlfile.write('</table>') exit(0)
Python Programming Language – Official Website
Python Documentation – CSV File Reading and Writing