Backend Development 13 min read

Using PrettyTable in Python to Create Formatted Command‑Line Tables

This article introduces the PrettyTable Python library, explains how to install it, demonstrates creating tables with headers, adding rows and columns, importing data from CSV, databases, or HTML, and shows various output formats and styling options for clear command‑line presentation.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Using PrettyTable in Python to Create Formatted Command‑Line Tables

When building command‑line tools on Linux, displaying structured data as readable tables greatly improves usability; the PrettyTable library provides this capability with excellent Unicode support.

Installation

PrettyTable is not part of the Python standard library and can be installed via pip install prettytable .

Basic Example

#!/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'])
table.add_row(['2','server02','服务器02','172.16.0.2'])
# ... additional rows omitted for brevity ...
print(table)

The script prints a neatly bordered table with Chinese column headers and data.

Adding Data

Data can be added row‑wise with table.add_row([...]) or column‑wise with table.add_column('列名', [...]) . The length of the data list must match the number of columns.

Importing from CSV

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

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

Use from_csv after opening a CSV file to populate the table automatically.

Importing from a Database Cursor

#!/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)

Query results from SQLite (or MySQL) can be turned into a PrettyTable directly.

Importing from HTML

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

html_string = '''
...
'''

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

The function returns a list containing a PrettyTable object; therefore the first element must be printed.

Output Formats

Standard printing ( print(table) ) shows a bordered ASCII table. For HTML output, use print(table.get_html_string()) .

Selective Output

Specific columns can be displayed with print(table.get_string(fields=["编号","IP地址"])) , and row ranges with print(table.get_string(start=0, end=2)) . Slicing syntax ( new_table = table[0:2] ) also works.

Sorting

Sort the table by a column using print(table.get_string(sortby="编号", reversesort=True)) .

Styling

Built‑in styles include MSWORD_FRIENDLY , PLAIN_COLUMNS , DEFAULT , and RANDOM . Set a style with table.set_style(DEFAULT) .

Custom Style

Attributes such as table.align[1] = 'l' , table.border , table.junction_char , table.horizontal_char , and table.vertical_char allow fine‑grained control over alignment and border characters.

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

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

table.align[1] = 'l'

table.border = True

table.junction_char = '$'

table.horizontal_char = '+'

table.vertical_char = '%'

print(table)

These settings produce a table with custom border characters and left‑aligned second column.

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

cliPythonSQLiteCSVData PresentationPrettyTableTable Formatting
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

login 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.