March 17, 2020

Today’s exercise is another in my continuing escapades in “stealth programming” using awk. I frequently write programs that produce CSV files as output. Most of the time the output file is loaded into Excel by the user. Sometimes the CSV file must be printed as well as loaded into Excel, and I wrote a program to do that in a previous exercise. I recently had a request to produce the output in HTML format, so I wrote that program yesterday.

Your task is to write a that converts a CSV file to HTML output; use whatever conventions make sense to you. When you are finished, you are welcome to read a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Pages: 1 2

4 Responses to “CSV To HTML”

  1. Daniel said

    Here’s a solution in Python.

    import csv
    import html
    import os
    import sys
    assert len(sys.argv) == 2
    html_lines = ['<html>', '<head></head>', '<body>', '<table>']
    with open(sys.argv[1]) as csvfile:
        reader = csv.DictReader(csvfile)
        html_lines.append('  <tr>')
        for name in reader.fieldnames:
            html_lines.append('    <th>' + html.escape(name) + '</th>')
        html_lines.append('  </tr>')
        for row in reader:
            html_lines.append('  <tr>')
            for name in reader.fieldnames:
                html_lines.append('    <td>' + html.escape(row[name]) + '</td>')
            html_lines.append('  </tr>')
    html_lines.extend(('</table>', '</body>', '</html>'))

    Example Output:





  2. Daniel said

    In my last comment, I tried pasting the HTML for the table itself, but it does not appear to work. Here’s another attempt, this time with the newlines removed.


  3. Great post! I really learned a lot from it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: