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()