Tabea-K
6/1/2016 - 12:23 PM

Converts a file in csv format into markdown (rather macdown) format.

Converts a file in csv format into markdown (rather macdown) format.

#!/usr/bin/env python
"""
Turns tab delimited data to macdown table format.
Needs the csvtoolkit to be installed.
"""
import sys
import os
import tempfile
import argparse


def check_if_tool_installed(toolname):
    """
    Checks, whether a tool is installed.
    Based on http://stackoverflow.com/a/11210185/897521
    """
    try:
        subprocess.call([toolname])
    except OSError as e:
        if e.errno == os.errno.ENOENT:
             # handle file not found error.
             sys.stderr.write("%s was not found! Please install %s!" % (toolname, toolname))
             exit (1)
        else:
             sys.stderr.write("%s couldn't start, please check if it is correctly installed!" % (toolname))
             exit (1)

# MAIN
if __name__ == "__main__":

    # parse arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('infile',
                        nargs='?',
                        type=argparse.FileType('r'),
                        default=sys.stdin)
    parser.add_argument("--H", "--H",
                        help="whether the csv data has a header",
                        default=False,
                        action="store_true")
    args = parser.parse_args()
    infile = args.infile

    temp_infile = False
    if infile.name == '<stdin>':
        temp_infile = tempfile.NamedTemporaryFile(delete=False)
        with open(temp_infile.name, 'w') as fh:
            for line in infile:
                fh.write(line)
        infile = temp_infile.name

    check_if_tool_installed('csvlook')

    temp_file = tempfile.NamedTemporaryFile(delete=False)
    if args.H:
        os.system('csvlook -t %s > %s' % (infile, temp_file.name))
    else:
        os.system('csvlook -t -H %s > %s' % (infile, temp_file.name))

    with open(temp_file.name, 'r') as fh:
        for i, line in enumerate(fh.readlines()):
            if set(line) == set('|+-\n'):
                if i == 2:
                    new_line = line.replace('+', '|')
                else:
                    continue
            else:
                new_line = line.strip().replace('\t', ' | ')
            if not new_line.strip() == "":
                print new_line.strip()

    os.remove(temp_file.name)
    if temp_infile:
        os.remove(temp_infile.name)