PrettyTable Tutorial

Python The PrettyTable Tutorial shows how to generate ASCII tables in Python using the PrettyTable module. In this tutorial, we use the PTable module, which is a fork of the original PrettyTable library.

PrettyTable

PrettyTable is a Python library for generating simple ASCII tables. It is inspired by the ASCII tables used in the PostgreSQL shell, psql. We can control many aspects of the table, such as the width of column padding, text alignment, or table borders. We can also sort the data.

We can also choose which columns and rows will be displayed in the final output. PrettyTable can read data from CSV, HTML, or a database cursor, and output data in ASCII or HTML.

PrettyTable Installation

$ sudo pip3 install PTable

We use the pip3 tool to install PrettyTable.

Generating PrettyTable

You can create a table using the add_row() or add_column() methods.

create_by_row.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable()

x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]

x.add_row(["Adelaide", 1295, 1158259, 600.5])
x.add_row(["Brisbane", 5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print(x)

This example uses the add_row() method to create a PrettyTable.

from prettytable import PrettyTable

From the module, we import PrettyTable.

x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]

We set the header names.

x.add_row(["Adelaide", 1295, 1158259, 600.5])
x.add_row(["Brisbane", 5905, 1857594, 1146.4])

These rows are added to the table using add_row().

print(x)

Finally, we print the table to the console.

$ ./create_by_row.py
+-----------+------+------------+------------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+------------------+
| Adelaide | 1295 | 1158259 | 600.5 |
| Brisbane | 5905 | 1857594 | 1146.4 |
| Darwin | 112 | 120900 | 1714.7 |
| Hobart | 1357 | 205556 | 619.5 |
| Sydney | 2058 | 4336374 | 1214.8 |
| Melbourne | 1566 | 3806092 | 646.9 |
| Perth | 5386 | 1554769 | 869.4 |
+-----------+------+------------+----------------+

This is the output.

In the next example, we create the same table using the add_column() method.

create_by_column.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable()

column_names = ["City name", "Area", "Population", "Annual Rainfall"]

x.add_column(column_names[0], ["Adelaide", "Brisbane", "Darwin",
    "Hobart", "Sydney", "Melbourne", "Perth"])
x.add_column(column_names[1], [1295, 5905, 112, 1357, 2058, 1566, 5386])
x.add_column(column_names[2], [1158259, 1857594, 120900, 205556, 4336374, 
3806092, 1554769]) 
x.add_column(column_names[3], [600.5, 1146.4, 1714.7, 619.5, 1214.8, 
646.9, 869.4])

print(x)

The column name is the first parameter of the add_column() method.

PrettyTable Deleting Rows

Use del_row() to delete a specific row. This method gets the index of the row to be deleted. Note that the index starts at zero.

delete_rows.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable()

x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]

x.add_row(["Adelaide", 1295, 1158259, 600.5])
x.add_row(["Brisbane", 5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

x.del_row(6)
x.del_row(5)
x.del_row(4)
x.del_row(3)

print(x)

In this example, we delete the last four rows.

$ ./delete_rows.py
+-----------+------+------------+----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide | 1295 | 1158259 | 600.5 |
| Brisbane | 5905 | 1857594 | 1146.4 |
| Darwin | 112 | 120900 | 1714.7 |
+-----------+------+------------+----------------+

The first three rows are retained in the output.

PrettyTable Clearing Data

The clear_rows() method deletes all rows from a table, but retains the current column names. The clear() method clears the row and column names.

clear_rows.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable()

x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]

x.add_row(["Adelaide", 1295, 1158259, 600.5])
x.add_row(["Brisbane", 5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

x.clear_rows()
print(x)

This example clears all rows from a table.

$ ./clear_rows.py
+-----------+------+------------+----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
+-----------+------+------------+-----------------+

This is the output of the example. The table header is not removed.

Generating PrettyTable from CSV

from_csv() can be used to generate a PrettyTable from CSV data.

data.csv

"City name", "Area", "Population", "Annual Rainfall"
"Adelaide", 1295, 1158259, 600.5
"Brisbane", 5905, 1857594, 1146.4
"Darwin", 112, 120900, 1714.7
"Hobart", 1357, 205556, 619.5
"Sydney", 2058, 4336374, 1214.8
"Melbourne", 1566, 3806092, 646.9
"Perth", 5386, 1554769, 869.4

data.csv contains comma-delimited data. Note that the first row consists of the table column names.

read_from_csv.py

#!/usr/bin/python3

from prettytable import from_csv

with open("data.csv", "r") as fp:

x = from_csv(fp)

print(x)

This example reads data from data.csv and generates a PrettyTable from it using from_csv().

Generating PrettyTable from a Database Cursor

The

from_db_cursor() method generates a PrettyTable from a database cursor.

cities.sql

DROP TABLE IF EXISTS Cities;

CREATE TABLE Cities(Id INTEGER PRIMARY KEY, Name TEXT, Area INTEGER,
    Population INTEGER, Rainfall REAL);

INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Adelaide", 1295, 1158259, 600.5);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Brisbane", 5905, 1857594, 1146.4);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Darwin", 112, 120900, 1714.7);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Hobart", 1357, 205556, 619.5);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Sydney", 2058, 4336374, 1214.8);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Melbourne", 1566, 3806092, 646.9);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Perth", 5386, 1554769, 869.4);

This is a SQL script for use in SQLite Create the Cities table in the database.

$ sqlite3 data.db
sqlite> .read cities.sql
sqlite> SELECT * FROM Cities;
Id Name Area Population Rainfall
---------- ---------- ---------- ---------- ----------
1 Adelaide 1295 1158259 600.5
2 Brisbane 5905 1857594 1146.4
3 Darwin 112 120900 1714.7
4 Hobart 1357 205556 619.5 
5 Sydney 2058 4336374 1214.8 
6 Melbourne 1566 3806092 646.9 
7 Perth 5386 1554769 869.4 

We read the cities.sql script, which generates the database tables.

read_from_cursor.py

#!/usr/bin/python3

import sqlite3 as lite
from prettytable import from_db_cursor

con = lite.connect('data.db')

with con:

cur = con.cursor()
cur.execute('SELECT * FROM Cities')

x = from_db_cursor(cur)

print(x)

In the code example, we connect to the data.db database and select all data from the Cities table. We use the from_db_cursor() method to generate a PrettyTable from the cursor.

Generate PrettyTable from HTML

from_html() generates a list of PrettyTables from a string of HTML code. Each <table> in the HTML becomes a PrettyTable object. from_html_one() generates a PrettyTable from a string of HTML code containing only a single <table>.

data.html

<html>
    <body>
        <table>
            <tr>
                <th>City name</th>
                <th>Area</th>
                <th>Population</th>
                <th>Annual Rainfall</th>
            </tr>
            <tr>
                <td>Adelaide</td>
                <td>1295</td>
                <td>1158259</td>
                <td>600.5</td>
            </tr>
            <tr>
                <td>Brisbane</td>
                <td>5905</td>
                <td>1857594</td>
                <td>1146.4</td>
            </tr>
            <tr>
                <td>Darwin</td>                <td>112</td>
                <td>120900</td>
                <td>1714.7</td>
            </tr>
            <tr>
                <td>Hobart</td>
                <td>1357</td>
                <td>205556</td>
                <td>619.5</td>
            </tr>
            <tr>
                <td>Sydney</td>
                <td>2058</td>
                <td>4336374</td>
                <td>1214.8</td>
            </tr>
            <tr>
                <td>Melbourne</td>
                <td>1566</td>
                <td>3806092</td>
                <td>646.9</td>
            </tr>
            <tr> <td>Perth</td>
<td>5386</td>
<td>1554769</td>
<td>869.4</td>
</tr>
</table>
</body>
</html>

In this example, we use this HTML file.

read_from_html.py

#!/usr/bin/python3

from prettytable import from_html_one

with open("data.html", "r") as fp:
html = fp.read()

x = from_html_one(html)
print(x)

This example reads data from the data.html file and generates a PrettyTable using the from_html_one() method.

Sorting Data

Using the sortby attribute, we specify the column to sort by. The reversesort attribute controls the direction of the sort (ascending or descending).

sorting.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable()
x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]

x.add_row(["Adelaide", 1295, 1158259, 600.5])
x.add_row(["Brisbane", 5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print("Table sorted by population:")
x.sortby = "Population"
print(x)

print()

print("Table sorted by city in descending order:")
x.sortby = "City name"
x.reversesort = True
print(x)

In this example, we sort the data in a table.

print("Table sorted by population:")
x.sortby = "Population"

First, we sort the data in ascending overall order.

x.sortby = "City name"
x.reversesort = True

Then, we sort the data in descending order by city name.

$ ./sorting.py
Table sorted by population:
+-----------+------+------------+------------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+------------------+
| Darwin | 112 | 120900 | 1714.7 |
| Hobart | 1357 | 205556 | 619.5 |
| Adelaide | 1295 | 1158259 | 600.5 |
| Perth | 5386 | 1554769 | 869.4 |
| Brisbane | 5905 | 1857594 | 1146.4 |
| Melbourne | 1566 | 3806092 |      646.9 |
| Sydney | 2058 | 4336374 | 1214.8 |
+-----------+------+------------+------------------+

Table sorted by city in descending order:
+-----------+------+------------+------------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+------------------+
| Sydney | 2058 | 4336374 | 1214.8 |
| Perth | 5386 | 1554769 | 869.4 |
| Melbourne | 1566 | 3806092 | 646.9 |
| Hobart | 1357 | 205556 | 619.5 |
| Darwin | 112 | 120900 | 1714.7 |
| Brisbane | 5905 | 1857594 | 1146.4 |
| Adelaide | 1295 | 1158259 | 600.5 |
+-----------+------+------------+-----------------+

This is the output.

Data Alignment

The align property controls the alignment of the field. Possible values are l, c, and r.

alignment.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable()

x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]

x.align["City name"] = "l"
x.align["Area"] = "r"
x.align["Annual Rainfall"] = "r"

x.add_row(["Adelaide", 1295, 1158259, 600.5])
x.add_row(["Brisbane", 5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print(x)

This code example aligns the data within a table column.

x.align["City name"] = "l"

We align the fields in the “City Name” column to the left.

x.align["Area"] = "r"
x.align["Annual Rainfall"] = "r"

We right-align the fields in “Area” and “Annual Rainfall.”

$ ./alignment.py
+-----------+------+------------+------------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+------------------+
| Adelaide | 1295 | 1158259 | 600.5 |
| Brisbane | 5905 | 1857594 | 1146.4 |
| Darwin | 112 | 120900 | 1714.7 |
| Hobart | 1357 | 205556 | 619.5 |
| Sydney | 2058 | 4336374 | 1214.8 |
| Melbourne | 1566 | 3806092 | 646.9 |
| Perth | 5386 | 1554769 | 869.4 |
+-----------+------+------------+-----------------+

This is the output.

HTML Output

get_html_string()Generates HTML output from PrettyTable.

html_output.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])

x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print(x.get_html_string())

This example prints the data from an HTML table to the console.

get_string Method

get_string() method returns a string representation of the table in its current state. It has several options to control how the table is displayed.

Show Title

Using the title parameter, we can include the table title in the output.

table_title.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])

x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print(x.get_string(title="Australian cities"))

This example creates a PrettyTable with a title.

$ ./table_title.py
+-------------------------------------------------+
| Australian cities |
+-----------+------+------------+------------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+------------------+
| Adelaide | 1295 | 1158259 | 600.5 |
| Brisbane | 5905 | 1857594 | 1146.4 |
| Darwin | 112 | 120900 | 1714.7 |
| Hobart | 1357 | 205556 | 619.5 |
| Sydney | 2058 | 4336374 | 1214.8 |
| Melbourne | 1566 | 3806092 | 646.9 |
| Perth | 5386 | 1554769 | 869.4 |
+-----------+------+------------+-----------------+

This is the output.

Selecting Columns

Using the fields option, we can select the columns to be displayed.

select_columns.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])

x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print(x.get_string(fields=["City Name", "Population"]))

In this example, we only display the “City Name” and “Population” columns.

$ ./select_columns.py
+-----------+------------+
| City name | Population |
+-----------+------------+
| Adelaide | 1158259 |
| Brisbane | 1857594 |
| Darwin | 120900 |
| Hobart | 205556 |
| Sydney | 4336374 |
| Melbourne | 3806092 |
| Perth | 1554769 |
+-----------+------------+

Selecting Rows

Using the start and end parameters, we can select which rows to display in the output.

select_rows.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])

x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print(x.get_string(start=1, end=4))

In this example, we only include three rows in the output.

$ ./select_rows.py
+-----------+------+------------+----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Brisbane | 5905 | 1857594 | 1146.4 |
| Darwin | 112 | 120900 | 1714.7 |
| Hobart | 1357 | 205556 | 619.5 |
+-----------+------+------------+----------------+

This is the output of the example.

In this tutorial, we have used the PrettyTable library to generate ASCII tables in Python.

You may also be interested in the following related tutorials: Matplotlib Tutorial and Python Tutorial, Python CSV Tutorial, SymPy Tutorial.

Leave a Reply

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