Skip to content
Snippets Groups Projects
html_writer.py 2.13 KiB
Newer Older
#!/usr/bin/env python3

import csv

def read_html():
    """
        Read the HTML template file into a string
    """
    with open("template.html") as htmlfile:
        htmlstring = htmlfile.read()
        return htmlstring


def read_csv(filename):
    """
        Read a csv file and produce a list of lists with each
        inner list representing a row in the csv file:
        [ [first, last, email], [first, last, email], ...]
    """
    result = []
    with open(filename) as csvfile:
        ### EDIT BELOW HERE ###
Mohammed Ahmed's avatar
Mohammed Ahmed committed
        row=[]
        reader = csv.reader(csvfile, delimiter=";")
Mohammed Ahmed's avatar
Mohammed Ahmed committed
        for row in reader:
            result.append(row)
        ### EDIT ABOVE HERE ###

    return result


def csv_to_html(csvdata):
    """
        Expects csvdata to be a list of lists:
        [ [first, last, email], [first, last, email], ...]

        Returns a string with the HTML <tbody> contents for
        each row in the csv file:
        <tr><td>First name</td><td>Last name</td><td>E-Mail</td></tr>"
    """
    htmlstring = ""
    ### EDIT BELOW HERE ###
Mohammed Ahmed's avatar
Mohammed Ahmed committed
    big_list=read_csv('test.csv')
    for row in big_list:
       htmlline = "<tr><td>{}</td><td>{}</td><td>{}</td></tr>\n"
    htmlstring=htmlstring+htmlline
    ### EDIT ABOVE HERE ###
    return htmlstring


def combine_template_with_data(template_string, htmldata):
    """
        Combine the HTML template string with the generated
        tabular data.
    """
    ### EDIT BELOW HERE ###
Mohammed Ahmed's avatar
Mohammed Ahmed committed
    fullstring=""
    i= ""
    i=csv_to_html('test.csv')
    with open('template.html','r',encoding='utf-8') as f:
        reader=f.read()
    fullstring=reader.replace('{}',i)
    return fullstring
    ### EDIT ABOVE HERE ###


def write_html(htmlstring):
    """
        Write the resulting HTML file
    """
    with open("result.html", "w") as htmlfile:
        htmlfile.write(htmlstring)


def main():
    """ 
        This is the main function of the program
    """
    template_string = read_html()
    csvdata = read_csv("test.csv")
    htmldata = csv_to_html(csvdata)
    fullstring = combine_template_with_data(template_string, htmldata)
    write_html(fullstring)

if __name__ == "__main__":
    main()