Skip to content

Instantly share code, notes, and snippets.

@hemanth
Forked from daleobrien/gist:3000515
Created June 27, 2012 05:12
Show Gist options
  • Save hemanth/3001632 to your computer and use it in GitHub Desktop.
Save hemanth/3001632 to your computer and use it in GitHub Desktop.
Function to print nicely formatted tables

Function to print ascii tables out.

>>> data = [["a", "b", "c"], [1, 2, 3], [4, 5, 60]]
>>> print_table(data, title="example")

+---+---+----+
| a | b |  c |
+---+---+----+
| 1 | 2 |  3 |
| 4 | 5 | 60 |
+---+---+----+

Code

def print_table(data, 
                filename=None,
                ascii=True,
                title=""):

    '''really fancy ascii table'''

    maxs = []

    if filename:
        f = open(filename, 'w')

    for row in data:
        for i, cell in enumerate(row):
            if len(maxs) <= i:
                maxs.append(0)
            if len(str(cell)) > maxs[i]:
                maxs[i] = len(str(cell))

    if ascii:
        tb = "+-" + "-+-".join(["-" * m for m in maxs]) + "-+"
        print
        if title:
            print "*** " + title + " ***"
            print
        print tb

    for j, row in enumerate(data):

        if filename:
            r = ",".join(["%s" % cell for cell in row])
            print >>f, r

        if ascii:
            text = []
            for i, cell in enumerate(row):

                if i > 0:
                    text.append(str(cell).rjust(maxs[i]))
                else:
                    text.append(str(cell).ljust(maxs[i]))

            print "| " + " | ".join(text) + " |"
            if j == 0:
                print tb
    if ascii:
        print tb

    if filename:
        f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment