簡介
Python通過PrettyTable模塊可以將輸出內(nèi)容如表格方式整齊地輸出扼鞋。
安裝
pip install prettytable
使用
直接創(chuàng)建
pt = PrettyTable()
從已有文件創(chuàng)建
CSV
from prettytable import from_csv
fp = open("mytable.csv", "r")
pt = from_csv(fp)
fp.close()
HTML
from prettytable import from_html
pt = from_html(html_string)
SQL
from prettytable import from_db_cursor
db_cur.execute("SELECT * FROM mytable")
pt = from_db_cursor(db_cur)
添加元素
按行添加
pt.add_row()
按列添加
pt.add_column()
輸出格式
ASCLL碼表
直接輸出
print(pt)
無表格框輸出
print(pt.get_string())
HTML表
print(pt.get_html_string())
選擇子表
print(pt.get_string(fields = ['city name', 'Population'] ))
#輸出前4列
print(pt.get_string(start = 0, end = 3))
or
new_table = old_table[0:3]
print(new_table)
控制表樣式
自帶樣式
#參數(shù)可以選擇DEFAULT PLAIN_COLUMNS
from prettytable import MSWORLD_FRIENDLY
x.set_style(MSWORLD_FRIENDLY)
print(x)