Skip to content

Instantly share code, notes, and snippets.

@ghing ghing/csv2md.py
Created Nov 8, 2014

Embed
What would you like to do?
Output GitHub Flavored Markdown tables for a CSV file
#!/usr/bin/env python
import csv
import sys
import click
def underlines(fieldnames):
underlines = []
for fieldname in fieldnames:
underline = ""
for i in range(len(fieldname)):
underline += "-"
underlines.append(underline)
return underlines
def order_row(fieldnames, row):
return [row[fn] for fn in fieldnames]
@click.command()
@click.argument('input', type=click.File('rb'), default=None, required=False)
def csv2md(input):
"""
Output a table formatted with GitHub Flavored Markdown from CSV
Examples:
Output Markdown for the first 8 rows of an Excel file.
in2csv openelex/us/ia/cache/20100608__ia__primary__adair__precinct.xls | head -n 8 | ./csv2md.py
"""
if input is None:
input = sys.stdin
reader = csv.DictReader(input)
sys.stdout.write(' | '.join(reader.fieldnames) + "\n")
sys.stdout.write(' | '.join(underlines(reader.fieldnames)) + "\n")
for row in reader:
sys.stdout.write(' | '.join(order_row(reader.fieldnames, row)) + "\n")
if __name__ == '__main__':
csv2md()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.