A simple Python library for easily displaying tabular data in a visually appealing ASCII table format
—
Utilities for creating PrettyTable instances from various data sources including CSV files, JSON data, HTML tables, database cursors, and MediaWiki markup. These functions simplify table creation from existing structured data.
Create tables from CSV files or file-like objects with configurable field names and parsing options.
def from_csv(fp, field_names: Sequence[str] | None = None, **kwargs) -> PrettyTable:
"""
Create PrettyTable from CSV file or file-like object.
Parameters:
- fp: File path, file object, or file-like object containing CSV data
- field_names: Sequence of field names (uses first row if None)
- **kwargs: Additional PrettyTable constructor arguments
Returns:
PrettyTable instance with CSV data loaded
"""Usage examples:
from prettytable import from_csv
# From file path
table = from_csv("data.csv")
# From file object
with open("data.csv", "r") as f:
table = from_csv(f)
# With custom field names
table = from_csv("data.csv", field_names=["Name", "Age", "City"])
# With formatting options
table = from_csv("data.csv", padding_width=2, align="l")
# From StringIO
import io
csv_data = "Name,Age\nAlice,25\nBob,30"
table = from_csv(io.StringIO(csv_data))Create tables from JSON strings with support for various JSON structures.
def from_json(json_string: str | bytes, **kwargs) -> PrettyTable:
"""
Create PrettyTable from JSON string.
Parameters:
- json_string: JSON formatted string or bytes containing table data
- **kwargs: Additional PrettyTable constructor arguments
Returns:
PrettyTable instance with JSON data loaded
"""Usage examples:
from prettytable import from_json
# From JSON array of objects
json_data = '''[
{"Name": "Alice", "Age": 25, "City": "New York"},
{"Name": "Bob", "Age": 30, "City": "Boston"}
]'''
table = from_json(json_data)
# With formatting options
table = from_json(json_data, align="l", padding_width=3)Extract tables from HTML markup with support for multiple tables per document.
def from_html(html_code: str, **kwargs) -> list[PrettyTable]:
"""
Create list of PrettyTables from HTML containing multiple tables.
Parameters:
- html_code: HTML string containing table elements
- **kwargs: Additional PrettyTable constructor arguments
Returns:
List of PrettyTable instances, one for each HTML table found
"""
def from_html_one(html_code: str, **kwargs) -> PrettyTable:
"""
Create single PrettyTable from HTML containing one table.
Parameters:
- html_code: HTML string containing exactly one table element
- **kwargs: Additional PrettyTable constructor arguments
Returns:
PrettyTable instance with HTML table data loaded
Raises:
Exception if HTML contains no tables or multiple tables
"""Usage examples:
from prettytable import from_html, from_html_one
# HTML with multiple tables
html_multi = '''
<table>
<tr><th>Name</th><th>Age</th></tr>
<tr><td>Alice</td><td>25</td></tr>
</table>
<table>
<tr><th>Product</th><th>Price</th></tr>
<tr><td>Widget</td><td>$10</td></tr>
</table>
'''
tables = from_html(html_multi) # Returns list of 2 tables
# HTML with single table
html_single = '''
<table>
<tr><th>Name</th><th>Score</th></tr>
<tr><td>Alice</td><td>95</td></tr>
<tr><td>Bob</td><td>87</td></tr>
</table>
'''
table = from_html_one(html_single) # Returns single table
# With formatting options
table = from_html_one(html_single, align="c", border=True)Create tables directly from database query results using cursor objects.
def from_db_cursor(cursor, **kwargs) -> PrettyTable | None:
"""
Create PrettyTable from database cursor.
Parameters:
- cursor: Database cursor object (sqlite3.Cursor or compatible)
- **kwargs: Additional PrettyTable constructor arguments
Returns:
PrettyTable instance with query results, or None if cursor is empty
"""Usage examples:
from prettytable import from_db_cursor
import sqlite3
# From SQLite cursor
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
cursor.execute("SELECT name, age, city FROM users")
table = from_db_cursor(cursor)
# With formatting options
cursor.execute("SELECT * FROM products")
table = from_db_cursor(cursor, align="l", padding_width=2)
# Handle empty results
cursor.execute("SELECT * FROM empty_table")
table = from_db_cursor(cursor) # Returns None if no results
conn.close()Parse MediaWiki table markup to create formatted tables.
def from_mediawiki(wiki_text: str, **kwargs) -> PrettyTable:
"""
Create PrettyTable from MediaWiki table markup.
Parameters:
- wiki_text: MediaWiki formatted table markup string
- **kwargs: Additional PrettyTable constructor arguments
Returns:
PrettyTable instance with MediaWiki table data loaded
"""Usage examples:
from prettytable import from_mediawiki
# MediaWiki table markup
wiki_markup = '''
{| class="wikitable"
|-
! Name !! Age !! City
|-
| Alice || 25 || New York
|-
| Bob || 30 || Boston
|}
'''
table = from_mediawiki(wiki_markup)
# With formatting options
table = from_mediawiki(wiki_markup, align="c", border=True)Internal HTML parser class used by HTML import functions, available for advanced use cases.
class TableHandler(HTMLParser):
"""HTML parser for converting HTML tables to PrettyTable objects."""
def __init__(self, **kwargs):
"""
Initialize HTML parser.
Parameters:
- **kwargs: PrettyTable constructor arguments
"""
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
"""Handle HTML start tags."""
def handle_endtag(self, tag: str) -> None:
"""Handle HTML end tags."""
def handle_data(self, data: str) -> None:
"""Handle HTML text data."""
def generate_table(self, rows: list[list[str]]) -> PrettyTable:
"""
Generate PrettyTable from parsed data.
Parameters:
- rows: List of row data from HTML parsing
Returns:
PrettyTable instance
"""
def make_fields_unique(self, fields: list[str]) -> list[str]:
"""
Ensure field names are unique.
Parameters:
- fields: List of field names
Returns:
List of unique field names
"""Usage example:
from prettytable import TableHandler
# Advanced HTML parsing
handler = TableHandler(align="l", padding_width=2)
handler.feed(html_string)
# Use handler methods for custom parsing logicFactory functions handle various error conditions gracefully:
from_csv() raises appropriate file system exceptionsfrom_json() raises JSON parsing exceptionsfrom_db_cursor() may raise database-specific exceptionsfrom_db_cursor()Example error handling:
try:
table = from_csv("nonexistent.csv")
except FileNotFoundError:
print("CSV file not found")
try:
table = from_json("invalid json")
except json.JSONDecodeError:
print("Invalid JSON format")
# Database cursor may return None
table = from_db_cursor(cursor)
if table is None:
print("No data returned from query")Install with Tessl CLI
npx tessl i tessl/pypi-prettytable