Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting csv file data with html template

I have an csv file, the data, and an HTML file, the template.

I want a script that will create an individual html file per record from the csv file, using the html file as a template.

Which is the best way to do this in Ruby? Python? Is there a tool/library I can use for this in either language?

like image 342
lamcro Avatar asked Jun 19 '09 13:06

lamcro


2 Answers

Python with Jinja2.

import jinja
import csv

env= jinja.Environment()
env.loader= jinja.FileSystemLoader("some/directory")
template= env.get_template( "name" )

rdr= csv.reader( open("some.csv", "r" ) )
csv_data = [ row for row in rdr ]

print template.render( data=csv_data )

It turns out that you might be able to get away with simply passing the rdr directly to Jinja for rending.

If the template looks like this, it will work with a wide variety of Python structures, including an iterator.

<table>
{% for row in data %}
<tr>
    <td>{{ row.0 }}</td><td>{{ row.1 }}</td>
</tr>
{% endfor %}
</table>
like image 167
S.Lott Avatar answered Oct 17 '22 07:10

S.Lott


Ruby has built in CSV handling which should make it fairly trivial to output static HTML files.
See:

  • http://www.rubytips.org/2008/01/06/csv-processing-in-ruby/
  • http://www.ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html

Actually, so does Python, so it's really a matter of personal preference (or of whichever you already have configured).

like image 45
Jon Avatar answered Oct 17 '22 05:10

Jon