Printing tabular data attractively in Python

Have you ever looked for a tool several times, not found what you wanted, then one fine day discover exactly what you were looking for by accident? I had just such an experience…

Not too infrequently in command line Python scripts, I want to output some textual data that is tabular in nature. I wrestled for a while with how to print out this sort of data in a way that’s readable, while not having to manually add line starting and ending characters, deal with padding and column alignment, separators, escape characters and all the other baggage that comes with ASCII shapes on the command line (at least ones that are broadly useful and don’t look like garbage).

When interacting with MySQL, Postgres, and other DB systems, their command line utilities provide just this sort of output already:

But what about cases where you simply have some data and need to print it into a table? Luke Maurits’ PrettyTable to the rescue! This module allows you to easily feed in data and print it in an ASCII table on the command line. It was actually just uploaded to PyPI today, so installation is now as easy as

1
sudo easy_install prettytable

While full documentation is available, the example Luke gives on the project homepage is sufficient to get started. Here is a shorter and more automated example:

1
2
3
4
5
6
7
8
9
10
from prettytable import PrettyTable
foo = PrettyTable()
foo.set_field_names(["Num", "Sum", "Double", "Triple"])
sum = 0
for n in range(1, 6):
    sum += n
    double = n * 2
    triple = n * 3
    foo.add_row([n, sum, double, triple])
foo.printt()

Running this returns:

It’s only version 0.1, but it has worked flawlessly and been a real lifesaver thus far.

Some additional features I’d like to help add at some point:

  • Allow formatting of various datatypes, such as adding commas to long numbers
  • Split headers across lines

Post to Twitter Post to Delicious Post to Digg Post to Reddit

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

This entry was posted in Programming and tagged , , . Bookmark the permalink.

4 Responses to Printing tabular data attractively in Python

  1. Kenny Meyer says:

    Now I definitely fell in love with the ‘prettytable’-module.

    Nice post!

  2. @Kenny Glad to share, it’s a great tool.

    Nice blog title BTW :-)

  3. Pingback: Sérgio Luiz Araújo Silva (voyeg3r) 's status on Sunday, 01-Nov-09 20:50:39 UTC - Identi.ca

  4. Pingback: Luke Maurits » Blog Archive » The unexpected success of PrettyTable

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>