TSV to HTML

Leif K-Brooks eurleif at ecritters.biz
Wed May 31 19:28:09 EDT 2006


Brian wrote:
> I was wondering if anyone here on the group could point me in a
> direction that would expllaing how to use python to convert a tsv file
> to html.  I have been searching for a resource but have only seen
> information on dealing with converting csv to tsv.  Specifically I want
> to take the values and insert them into an html table.

import csv
from xml.sax.saxutils import escape

def tsv_to_html(input_file, output_file):
     output_file.write('<table><tbody>\n')
     for row in csv.reader(input_file, 'excel-tab'):
         output_file.write('<tr>')
         for col in row:
             output_file.write('<td>%s</td>' % escape(col))
         output_file.write('</tr>\n')
     output_file.write('</tbody></table>')

Usage example:

 >>> from cStringIO import StringIO
 >>> input_file = StringIO('"foo"\t"bar"\t"baz"\n'
...                       '"qux"\t"quux"\t"quux"\n')
 >>> output_file = StringIO()
 >>> tsv_to_html(input_file, output_file)
 >>> print output_file.getvalue()
<table><tbody>
<tr><td>foo</td><td>bar</td><td>baz</td></tr>
<tr><td>qux</td><td>quux</td><td>quux</td></tr>
</tbody></table>



More information about the Python-list mailing list