Last active
November 12, 2018 11:43
-
-
Save mrtj/de0b8d79eecb49509db9d51f1119b891 to your computer and use it in GitHub Desktop.
Convert a CSV file to a Markdown table
This file contains hidden or 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
from __future__ import print_function | |
import csv | |
def print_row(row, maxlen): | |
for elem, len in zip (row, maxlen): | |
print('| {} '.format(elem.ljust(len)), end='') | |
print('|') | |
def print_hline(maxlen): | |
for len in maxlen: | |
print('| {} '.format(''.ljust(len, '-')), end='') | |
print('|') | |
def csv2md(filename, has_header=True): | |
with open(filename, newline='') as csvfile: | |
sniffer = csv.Sniffer() | |
dialect = sniffer.sniff(csvfile.read(1024)) | |
csvfile.seek(0) | |
reader = csv.reader(csvfile, dialect) | |
maxlen = None | |
rows = [] | |
for row in reader: | |
if maxlen is None: | |
maxlen = [0] * len(row) | |
else: | |
maxlen = [max(maxlen[i], len(row[i])) for i in range(len(maxlen))] | |
rows.append(row) | |
for idx, row in enumerate(rows): | |
print_row(row, maxlen) | |
if has_header and idx == 0: | |
print_hline(maxlen) | |
if __name__ == '__main__': | |
import argparse | |
parser = argparse.ArgumentParser(description='Converts a CSV file to a Markdown table.') | |
parser.add_argument('filename', help='name of the csv file') | |
parser.add_argument('--no_header', '-nh', | |
help='The CSV file has no header', action='store_true') | |
args = parser.parse_args() | |
csv2md(args.filename, not args.no_header) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage: