prettytable
用於打印表格
import prettytable as pt
# tb = pt.PrettyTable( ["City name", "Area", "Population", "Annual Rainfall"])
tb = pt.PrettyTable()
tb.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
tb.add_row(["Adelaide",1295, 1158259, 600.5])
tb.add_row(["Brisbane",5905, 1857594, 1146.4])
tb.add_row(["Darwin", 112, 120900, 1714.7])
tb.add_row(["Hobart", 1357, 205556,619.5])
tb.add_column('index',[1,2,3,4]) #* 添加一列 *
print(tb)
結果:
+-----------+------+------------+-----------------+-------+
| City name | Area | Population | Annual Rainfall | index |
+-----------+------+------------+-----------------+-------+
| Adelaide | 1295 | 1158259 | 600.5 | 1 |
| Brisbane | 5905 | 1857594 | 1146.4 | 2 |
| Darwin | 112 | 120900 | 1714.7 | 3 |
| Hobart | 1357 | 205556 | 619.5 | 4 |
+-----------+------+------------+-----------------+-------+
- add_row() :按行添加数据,添加的数据必须要是列表(list)的形式,而且数据的列表长度要和表头的长度一样。
- add_column():按列添加數據。
从csv文件添加数据
import prettytable as pt
from prettytable import from_csv
table = pt.PrettyTable()
with open('res.csv', 'r') as f:
table = from_csv(fp)
print(table)
对齐方式
align
提供了用户设置对齐的方式,值有 l,r,c
方便代表 左对齐,右对齐和居中
如果不设置,默认居中对齐。
tb.align["City name"] = "l"
tb.align["Area"] = "c"
tb.align["Population"] = "r"
tb.align["Annual Rainfall"] = "c"
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide | 1295 | 1158259 | 600.5 |
| Brisbane | 5905 | 1857594 | 1146.4 |
| Darwin | 112 | 120900 | 1714.7 |
| Hobart | 1357 | 205556 | 619.5 |
+-----------+------+------------+-----------------+
詳細應用參考:python prettytable 打印表格