Fundamentals 14 min read

Master PrettyTable: Create Beautiful CLI Tables in Python

This tutorial explains how to use the Python PrettyTable library to generate well‑formatted command‑line tables, covering installation, row and column insertion, data import from CSV, databases and HTML, various output formats, selective printing, sorting, and custom styling options.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Master PrettyTable: Create Beautiful CLI Tables in Python

1. Introduction

When building a small Python tool on a Linux workstation to manage resources such as Alibaba Cloud ECS instances, displaying information in a plain command‑line list can be hard to read. PrettyTable provides a way to print attractive tables with excellent Chinese character support.

2. Installation

PrettyTable is not part of the Python standard library. Install it with:

pip install prettytable

3. Basic Example

The following script creates a table with headers ['ID','Cloud ID','Name','IP Address'] and adds several rows:

#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
from prettytable import PrettyTable
reload(sys)
sys.setdefaultencoding('utf8')

table = PrettyTable(['编号','云编号','名称','IP地址'])

table.add_row(['1','server01','服务器01','172.16.0.1'])
# ... add more rows similarly ...
print(table)

The output shows a neatly bordered table.

4. Adding Data

Adding Rows with add_row

Rows must be provided as a list whose length matches the number of columns. Ensure the data aligns with the header fields.

Adding Columns with add_column

You can also add data column‑wise:

table.add_column('项目', ['编号','云编号','名称','IP地址'])
table.add_column('值', ['1','server01','服务器01','172.16.0.1'])
print(table)

Importing from CSV

PrettyTable can read a CSV file directly:

#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
from prettytable import PrettyTable, from_csv
reload(sys)
sys.setdefaultencoding('utf8')

fp = open('res.csv', 'r')
table = from_csv(fp)
print(table)
fp.close()

Make sure the file has a .csv extension; Excel files renamed to .csv may cause errors.

Importing from a Database

Query results from SQLite (or MySQL) can be turned into a table:

#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys, sqlite3
from prettytable import PrettyTable, from_db_cursor
reload(sys)
sys.setdefaultencoding('utf8')

conn = sqlite3.connect('/tmp/aliyun.db')
cur = conn.cursor()
cur.execute('SELECT * FROM res')

table = from_db_cursor(cur)
print(table)

Importing from HTML

HTML tables can be parsed with from_html:

#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
from prettytable import PrettyTable, from_html
reload(sys)
sys.setdefaultencoding('utf8')

html_string = '''<table>
<tr><th>编号</th><th>云编号</th><th>名称</th><th>IP地址</th></tr>
<tr><td>1</td><td>server01</td><td>服务器01</td><td>172.16.0.1</td></tr>
<tr><td>2</td><td>server02</td><td>服务器02</td><td>172.16.0.2</td></tr>
</table>'''

table = from_html(html_string)
print(table[0])

Note that from_html returns a list containing a PrettyTable object, so you need to print table[0].

5. Output Formats

Printing the table directly ( print(table)) shows a bordered ASCII table. To get HTML output, use:

print(table.get_html_string())

6. Selective Output

You can print specific columns:

print(table.get_string(fields=["编号", "IP地址"]))

Or limit rows by index:

print(table.get_string(start=0, end=2))

Tables also support slicing, e.g., new_table = table[0:2] and then print(new_table).

7. Sorting

Sort the table by a column, optionally in reverse order:

print(table.get_string(sortby="编号", reversesort=True))

8. Table Styles

Built‑in Styles

Use set_style() to apply predefined styles such as MSWORD_FRIENDLY, PLAIN_COLUMNS, DEFAULT, or RANDOM for a random style.

Custom Styles

Adjust alignment per column ( l, r, c), and control border characters:

table.align[1] = 'l'          # left‑align second column
table.border = True
table.junction_char = '$'
table.horizontal_char = '+'
table.vertical_char = '%'
print(table)

The example above produces a table with custom border symbols.

For more details, refer to the official PrettyTable documentation: https://github.com/jazzband/prettytable

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

CLITutorialformattingdata importprettytableTable
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.