Wednesday, October 4, 2017

Dynamically generate HTML file from CSV data using Python

Hello there,

Assuming you have bunch of dataset in a CSV file and you want to dynamically add them on to a HTML file to upload on a web server so the someone on the other part part of the world could access and view it on the web. And you don't want to share the raw CSV file instead you want a to share a viewer friendly file such HTML, then this article is for you.

Below is the out of the script that collects data from a CSV file and populate a HTML file.



The script is as simple as below...

So, basically we just import the CSV module and read in the csv file. Then we used the open() method to create a html file in the working directory and write lines of standard html code in it.

import csv


csv_list = []
      
try:
    with open('registrant_data.csv', 'rU') as csvfile:
        readCSV = csv.reader(csvfile)
        for row in readCSV:
            csv_list.append(row)
 # ========= Create html file ================

    with open('../nametags8gen.html','w') as html8:
        html8.write('<html>')
        html8.write('<head><title>Title of the page...</title> <link rel="stylesheet" type="text/css" href="./nametags8gen.css"></link></head>')
        html8.write('<body>')
 # more algorithms to fetch csv records...

        html8.write('</html>')
        html8.write('</body>')
         

To generate new html with new contents, just update the CSV file and run the script.

That is it.
Thanks for following...

No comments:

Post a Comment