PrettyTable is a python library designed to display tabular data in a visually appealing ASCII table. It generates tables similar to one used in PostgreSQL shell psql.
PrettyTable can be installed using pip. In Windows, pip is available under "script" directory and in linux under "bin" directory of Python's installation path.
pip install prettytable
Once it is installed, check if we can import prettytable using below command :
import prettytable
from prettytable import PrettyTable
table = PrettyTable(['Coin', 'Price', 'High', 'Low'])
table.add_row(['BTC', '14525.00 USD', '15355.00 USD', '13755.00 USD'])
table.add_row(['ETH', '1191.00 USD', '1250.00 USD', '965.18 USD'])
table.add_row(['XRP', '2.25 USD', '2.49 USD', '1.90 USD'])
table.add_row(['LTC', '247.72 USD', '258.04 USD', '230.18 USD'])
table.add_row(['MIOTA', '3.64 USD', '3.95 USD', '3.15 USD'])
print(table)
from_csv() method from prettytable.from prettytable import from_csv
Open the CSV file in read mode.
with open('data.csv', 'r') as f:
Read the content of CSV file. Then use from_csv() method on the read content and store it in a variable.
table = from_csv(f)
Set the columns to left justified.
table.align = 'l'
Print the table.
print(table)
from_html_one() method from prettytable.from prettytable import from_html_one
with open('data.html', 'r') as f:
html_data = f.read()
from_html_one() method and pass the read html content and store it in a variable.table = from_html_one(html_data)
table.align = 'l'
print(table)
Using PrettyTable python library we can quickly and easily represent tabular data in nice CLI tables. Apart from above examples, it can be used for printing range of rows or selected columns. It can also be used to display table by sorting a given column.
If you have any questions, comments or have used PrettyTable before, I'd would love to hear from you in comment section.