Skip to content

Instantly share code, notes, and snippets.

@akosma
Created November 20, 2016 16:25
Show Gist options
  • Save akosma/fc2b84baebd3941c2bdb474a754e3150 to your computer and use it in GitHub Desktop.
Save akosma/fc2b84baebd3941c2bdb474a754e3150 to your computer and use it in GitHub Desktop.
Script to convert simple CSV files into a Markdown table compatible with Deckset
#!/usr/bin/env python
import csv
import sys
if len(sys.argv) < 2:
print('Requires a file as parameter')
exit(1)
# Courtesy of
# http://stackoverflow.com/a/904085/133764
def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs):
csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs)
for row in csv_reader:
yield [unicode(cell, 'utf-8') for cell in row]
def read_file(filename):
lines = []
reader = unicode_csv_reader(open(filename))
for row in reader:
lines.append(row)
return lines
# First pass to gather size of each column
def get_column_sizes(lines):
sizes = []
for row in lines:
current_column = 0
for word in row:
if len(sizes) <= current_column:
sizes.append(0)
current_length = len(word) + 2
current_max = sizes[current_column]
if current_length > current_max:
sizes[current_column] = current_length
current_column += 1
return sizes
# Second pass to generate the Markdown table
def generate_table(lines, sizes):
rows = []
first_row = True
for row in lines:
current_column = 0
for word in row:
rows.append(u'| ' + word + (u' ' * (sizes[current_column] - len(word) - 1)))
current_column += 1
if first_row:
rows.append(u'|\n')
col = 0
for word in row:
rows.append(u'|' + (u'-' * (sizes[col])))
col += 1
first_row = False
rows.append(u'|\n')
return rows
filename = str(sys.argv[1])
lines = read_file(filename)
sizes = get_column_sizes(lines)
table = generate_table(lines, sizes)
str = ''.join(table)
print(str)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment