Code Self Study Forum

Python Pretty Table

This package was mentioned at the meetup today:
http://zetcode.com/python/prettytable/

Example:

"""
Don't forget:

    $ pip install ptable
"""
from prettytable import PrettyTable

# example: read in some text file
data = '''
3,alice,apples
7,bob,beets
10,charlie,cabbage
'''.strip()

headers = ['id', 'name', 'food']
rows = data.split('\n')

# create a table object
t = PrettyTable()

# add the items to the table
[t.add_row(row.split(',')) for row in rows]
t.field_names = headers

print(t)

Running the program:

$ python app.py
+----+---------+---------+
| id |   name  |   food  |
+----+---------+---------+
| 3  |  alice  |  apples |
| 7  |   bob   |  beets  |
| 10 | charlie | cabbage |
+----+---------+---------+

The tables are Org Mode compatible.

1 Like

Ooh I think I’ve needed this for quite a while. Thanks for posting it!