Simple formatted tables in python with Texttable

Simple formatted tables in python with Texttable module

Texttable is a python package written by Gerome Fournier, which can be used to produce simple formatted tables. The table produced can include a header with title for each column and separated from the first row with a line drawn using a user specified character. Lines of character can also be inserted between rows, between columns and around the border of the table. This module has methods for inserting lists as rows and as header.

A Texttable object is initialized as follows:

import texttable as tt
tab = tt.TextTable()

To insert a header we create a list with each element containing the title of a column and then add it to the table using the header() method of the TextTable object.

header = ['Manager', 'Club', 'Year']
tab.header(header)

The header can also be added as the first row of the table.

To insert a row into the table, we create a list with the elements of the row and add it to the table using the add_row() method of the TextTable object. Multiple rows can be added using the add_rows method as shown in the example at the end.

row = ['Ottmar Hitzfeld', 'Borussia Dortmund, Bayern Munich',\
 '1997 and 2001']
tab.add_row(row)
row = ['Ernst Happel', 'Feyenoord, Hamburg', '1970 and 1983']
tab.add_row(row)
row = ['Jose Mourinho', 'Porto, Inter Milan', '2004 and 2010']
tab.add_row(row)

We can set the width of the table cells using the set_cols_width() method. The input is a list of integers specifying the width of the columns in the table.

tab.set_cols_width([18,35,15])

We can set the horizontal and vertical alignment of data within table cells using the methods set_cols_align() and set_cols_valign() respectively. Each take as input a list, of length the same as the number of items in a row of the table. For set_cols_align(), the list can containing the characters ‘l’ for left alignment, ‘c’ for center alignment and ‘r’ for right alignment. For the set_cols_valign() method, the list can contain the characters ‘t’ for top alignment, ‘m’ for middle alignment and ‘b’ for bottom alignment.

tab.set_cols_align(['l','r','c'])
tab.set_cols_valign(['t','b', 'm'])

The method set_deco() can be used to control the drawing of lines between rows and columns and between the header and the first row. This function takes a combination of the following four constants, the presence of which turns on the particular feature:

  1. texttable.BORDER: border drawn around the table
  2. texttable.HEADER: line below the header
  3. texttable.HLINES: lines between rows
  4. texttable.VLINES: lines between columns

By default all the above are set. The following code turns off the border drawn around the table and the horizontal lines drawn between rows and activates lines drawn between columns and the line drawn between the header and the first row.

tab.set_deco(tab.HEADER | tab.VLINES)

The characters used to draw the various lines can be set using the set_chars() method. This method takes a list of length 4, the elements of which determine the character used for horizontal lines, vertical lines, intersection points of these lines, and the header line, in that order. The default list is [‘-‘, ‘|’, ‘+’, ‘=’]. The following code sets the character used to draw a line under the header to ‘#’.

tab.set_chars(['-','|','+','#'])

The table is returned as a string when the method draw() is called.

s = tab.draw()
print s

The above code snippets produce the following result:

     Manager       |                Club                 |      Year
###################+#####################################+################
Ottmar Hitzfeld    |    Borussia Dortmund, Bayern Munich |  1997 and 2001
Ernst Happel       |                  Feyenoord, Hamburg |  1970 and 1983
Jose Mourinho      |                  Porto, Inter Milan |  2004 and 2010

.
The following is an example of creating a table from a 2 dimensional list. This code uses the add_rows() method, which accepts an iterator or a multi-dimensional list.

import texttable as tt

tab = tt.Texttable()

x = [[]] # The empty row will have the header

for i in range(1,11):
    x.append([i,i**2,i**3])

tab.add_rows(x)
tab.set_cols_align(['r','r','r'])
tab.header(['Number', 'Number Squared', 'Number Cubed'])
print tab.draw()
+--------+----------------+--------------+
| Number | Number Squared | Number Cubed |
+========+================+==============+
|      1 |              1 |            1 |
+--------+----------------+--------------+
|      2 |              4 |            8 |
+--------+----------------+--------------+
|      3 |              9 |           27 |
+--------+----------------+--------------+
|      4 |             16 |           64 |
+--------+----------------+--------------+
|      5 |             25 |          125 |
+--------+----------------+--------------+
|      6 |             36 |          216 |
+--------+----------------+--------------+
|      7 |             49 |          343 |
+--------+----------------+--------------+
|      8 |             64 |          512 |
+--------+----------------+--------------+
|      9 |             81 |          729 |
+--------+----------------+--------------+
|     10 |            100 |         1000 |
+--------+----------------+--------------+
Advertisements
This entry was posted in Python and tagged . Bookmark the permalink.

6 Responses to Simple formatted tables in python with Texttable

  1. Pingback: Find on beautiful soup in loop returns TypeError

  2. Elli says:

    Thank you for the nice introduction. There is only one comment:
    tab = tt.TextTable() is written wrong, it must be tt.Texttable() with a smal t in table.

  3. hamood says:

    thank you sir
    that’s was a big help for my project

  4. Raptor says:

    Great!

    Please just change:
    tab = tt.TextTable()
    to
    tab = tt.Texttable()

    tt has only the followings:
    [‘ArraySizeError’, ‘Texttable’, ‘__all__’, ‘__author__’, ‘__builtins__’, ‘__credits__’, ‘__doc__’, ‘__file__’, ‘__license__’, ‘__name__’, ‘__package__’, ‘__version__’, ‘len’, ‘reduce’, ‘string’, ‘sys’, ‘textwrap’]

  5. Pingback: Python:Is there a tool in Python to create text tables like Powershell? – IT Sprite

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s