How To Read A CSV Into A HTML Table With Python

A lot can been done with a CSV (“comma separated value”) file.

If you can run a web scraping script on your local machine, you can FTP the results to a FTP site in the ubiquitous CSV format, and then render it on your web page with HTML.

The rest of this post demonstrates a basic example of how you can read a CSV file into an HTML table using Python.

Add an iframe to your page and point it to your python (py) file:

Here is the code for the file:


#!/usr/bin/python
#import csv  #the module is already present so no need to add it again


#MAKE SURE THE FILE PERMISSIONS ARE 755!!!!

filename = open('file_to_ftp.csv') 


# print HTTP header
print "Content-type: text/html\n\n"

# define an HTML template
print "<!DOCTYPE html>"
print "<html>"
print "<head>"
print "<title>CSVParse</title>"
print "</head>"
print "<body>"

print("<table style='width:100%'>")

print("<tr>")
print("<th>Index</th>")
print("<th>Company</th>")
print("<th>Link</th>")
print("<th>Header</th>")

print("</tr>")

for line in filename:	
    row = line.split(",")
    print("<tr>")
    print ("<td>" + str(row[0]) + "</td>")
    print ("<td>" + str(row[1]) + "</td>")
    print ("<td>" + str(row[2]) + "</td>")
    print ("<td>" + str(row[3]) + "</td>")
    print ("</tr>")


print("</table>")


print "</body>"
print "</html>"


Click here for the file in action.

Let me know if you need assistance.

Facebooktwitterredditpinterestlinkedinmail
Tags:
 
Next Post

How To Use JQuery In Python Without Importing New Modules