Seeing a csv in table form is nicer then viewing it as row text, for example the csv from Calculate food company sales for the year (with headers added by me) looks much nicer in this table form than in plain-text:
<table border="1">
<tr>
<th> Kind</th>
<th> Brand</th>
<th> Sales in 2014</th>
<th> Sales in 2015</th>
</tr>
<tr>
<td> Cereal</td>
<td>Magic Balls</td>
<td>2200</td>
<td>2344
</tr>
<tr>
<td> Cereal</td>
<td>Kaptain Krunch</td>
<td>3300</td>
<td>3123
</tr>
<tr>
<td> Cereal</td>
<td>Coco Bongo</td>
<td>1800</td>
<td>2100
</tr>
<tr>
<td> Cereal</td>
<td>Sugar Munch</td>
<td>4355</td>
<td>6500
</tr>
<tr>
<td> Cereal</td>
<td>Oats n Barley</td>
<td>3299</td>
<td>5400
</tr>
<tr>
<td> Sugar Candy</td>
<td>Pop Rocks</td>
<td>546</td>
<td>982
</tr>
<tr>
<td> Sugar Candy</td>
<td>Lollipop</td>
<td>1233</td>
<td>1544
</tr>
<tr>
<td> Sugar Candy</td>
<td>Gingerbud</td>
<td>2344</td>
<td>2211
</tr>
<tr>
<td> Sugar Candy</td>
<td>Respur</td>
<td>1245</td>
<td>2211
</tr>
<tr>
<td> Chocolate</td>
<td>Coco Jam</td>
<td>3322</td>
<td>4300
</tr>
<tr>
<td> Chocolate</td>
<td>Larkspur</td>
<td>1600</td>
<td>2200
</tr>
<tr>
<td> Chocolate</td>
<td>Mighty Milk</td>
<td>1234</td>
<td>2235
</tr>
<tr>
<td> Chocolate</td>
<td>Almond Berry</td>
<td>998</td>
<td>1233
</tr>
<tr>
<td> Condiments</td>
<td>Peanut Butter</td>
<td>3500</td>
<td>3902
</tr>
<tr>
<td> Condiments</td>
<td>Hot Sauce</td>
<td>1234</td>
<td>1560
</tr>
<tr>
<td> Condiments</td>
<td>Jelly</td>
<td>346</td>
<td>544
</tr>
<tr>
<td> Condiments</td>
<td>Spread</td>
<td>2334</td>
<td>5644</tr></table>
To view a .csv
file, I just translate it into HTML and call the browser on it.
The code is short because the task is simple, but I feel like it could be written better:
"""
This utility shows a csv file in table format
by translating it to html and calling the browser on the newly created file.
The html file is not deleted after being viewed
and has name `original_file.split('.')[0] + '.html'`
Example usage:
python3 csview.py example.csv
"""
import webbrowser
import sys
def csv_to_html(csv):
START = '''<table border="1">\n\n'''
END = '''</tr></table>'''
lines = [line for line in csv.split("\n") if line]
html_lines = ["<th>" + lines[0].replace(',', '</th>\n<th>') + '</th>'] +\
["<td>" + line.replace(',', '</td>\n<td>') for line in lines[1:]]
body = '<tr>\n' + '\n</tr>\n\n<tr>\n'.join(html_lines)
return START + body + END
if __name__ == "__main__":
html_filename = sys.argv[1].split('.')[0] + '.html'
with open(html_filename, "w+") as out_file:
with open(sys.argv[1]) as in_file:
out_file.write(csv_to_html(in_file.read()))
webbrowser.open(html_filename)