简体   繁体   中英

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?

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>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM