【Python】prettytable

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 打印表格

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值