-
-
Save yoavram/c043d8ee9e044be2eb6b to your computer and use it in GitHub Desktop.
csv table 2 rst
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import sys | |
import csv | |
try: | |
import click | |
except ImportError as e: | |
print("Please install Click: http://click.pocoo.org") | |
sys.exit(1) | |
PROG_NAME = __file__ | |
VERSION = '0.0.1' | |
def underline(title, out, underliner="=", endl="\n"): | |
''' | |
write *title* *underlined* to *out* | |
''' | |
out.write(title) | |
out.write(endl) | |
out.write(underliner * len(title)) | |
out.write(endl * 2) | |
def separate(sizes, out, separator="=", endl="\n"): | |
''' | |
write the separators for the table using sizes to get the | |
size of the longest string of a column | |
''' | |
for size in sizes: | |
out.write(separator * size) | |
out.write(" ") | |
out.write(endl) | |
def write_row(sizes, items, out, endl="\n"): | |
''' | |
write a row adding padding if the item is not the | |
longest of the column | |
''' | |
for item, max_size in zip(items, sizes): | |
item_len = len(item) | |
out.write(item) | |
if item_len < max_size: | |
out.write(" " * (max_size - item_len)) | |
out.write(" ") | |
out.write(endl) | |
@click.command() | |
@click.argument('input_file', type=click.File('r')) | |
@click.argument('output_file', default='-', type=click.File('w', lazy=True)) | |
@click.option('-t', '--title', default='', help='title', type=str) | |
@click.version_option(version=VERSION, prog_name=PROG_NAME) | |
def run(input_file, output_file, title=''): | |
''' | |
read a CSV table from INPUT FILE and write the reStructuredText table to OUTPUT FILE (or to stdout if not given). | |
''' | |
reader = csv.reader(input_file) | |
rows = [row for row in reader if row] | |
cols = len(rows[0]) | |
sizes = [0] * cols | |
for i in range(cols): | |
for row in rows: | |
row_len = len(row[i]) | |
max_len = sizes[i] | |
if row_len > max_len: | |
sizes[i] = row_len | |
if title: | |
underline(title) | |
separate(sizes, output_file) | |
write_row(sizes, rows[0], output_file) | |
separate(sizes, output_file) | |
for row in rows[1:]: | |
write_row(sizes, row, output_file) | |
separate(sizes, output_file) | |
if __name__ == "__main__": | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment