Prettytable in Python
1. Introduction
PrettyTable is a Python library used to create visually appealing tables in text format. It is especially useful for displaying tabular data in a structured and readable way. It allows users to add columns and rows dynamically, format the output, and customize styles.
2. Installation
To use PrettyTable, you need to install it first. You can install it using pip:
pip install prettytable
3. Importing PrettyTable
Once installed, you can import it into your Python script:
from prettytable import PrettyTable
4. Creating a Simple Table
You can create a table by defining column names and adding rows.
4.1 Creating a Table Object
from prettytable import PrettyTable
# Create a PrettyTable object
table = PrettyTable()
# Define column names
table.field_names = ["ID", "Name", "Age", "Country"]
# Add rows of data
table.add_row([1, "Alice", 25, "USA"])
table.add_row([2, "Bob", 30, "Canada"])
table.add_row([3, "Charlie", 28, "UK"])
# Print the table
print(table)
Output:
+----+---------+-----+---------+
| ID | Name | Age | Country |
+----+---------+-----+---------+
| 1 | Alice | 25 | USA |
| 2 | Bob | 30 | Canada |
| 3 | Charlie | 28 | UK |
+----+---------+-----+---------+
5. Adding Rows and Columns
You can add rows using:
table.add_row(["4", "David", 22, "Germany"])
Or add multiple rows at once:
table.add_rows([
[5, "Eve", 26, "Australia"],
[6, "Frank", 29, "India"]
])
Adding columns:
table.add_column("Gender", ["F", "M", "M", "M", "F", "M"])
6. Changing Table Appearance
6.1 Adjusting Table Alignment
You can align the text inside the columns:
table.align["Name"] = "l" # Left align
table.align["Country"] = "r" # Right align
print(table)
6.2 Adjusting Table Borders
Removing borders:
table.border = False
print(table)
Adding a different horizontal character:
table.horizontal_char = "*"
print(table)
Changing vertical characters:
table.vertical_char = "!"
print(table)
6.3 Changing Header and Row Styles
You can change the column headers to uppercase:
table.field_names = [header.upper() for header in table.field_names]
You can set table style to MS Word style:
table.set_style("MSWORD_FRIENDLY")
print(table)
7. Sorting Data
You can sort a table by a specific column:
table.sortby = "Age"
print(table)
Sort in descending order:
table.sortby = "Age"
table.reversesort = True
print(table)
8. Using PrettyTable with Pandas
If you have a pandas.DataFrame, you can convert it into a PrettyTable:
import pandas as pd
data = {
"ID": [1, 2, 3],
"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 28]
}
df = pd.DataFrame(data)
table = PrettyTable()
table.field_names = df.columns.tolist()
for row in df.itertuples(index=False):
table.add_row(row)
print(table)
9. Exporting Tables
You can export a table to a string:
table_str = table.get_string()
with open("table.txt", "w") as f:
f.write(table_str)
10. Conclusion
PrettyTable is a powerful library for displaying structured data in pretty output. Very flexible, supports sorting, alignment, and many different styles, this makes it really useful in command-line applications, debugging, and reporting.