目录
一、说明
二、安装
三、导入
一、说明
PrettyTable 是python中的一个第三方库,可用来生成美观的ASCII格式的表格,十分实用
二、安装
使用pip即可十分方便的安装PrettyTable(命令行窗口安装),如下:
先windows+R打开命令行窗口
然后输入pip install PrettyTable
三、导入
from prettytable import PrettyTable 或者 import prettytable as pt
四、基本使用
1、创建表格
2、设置表的名称
3、按行/列添加数据:
4、一次性添加多行
注意:add_column的第一个参数表示列的字段名,为字符串,第二个参数为列表,即添加到该列的数据。没有一次性添加多列的方法。
5、根据CSV导入
PrettyTable不仅提供了手动按行按列添加数据,也支持直接从csv文件中读取数据,需要注意的是,字符串需要加上引号。如果要读取cvs文件数据,必须要先导入from_csv,否则无法运行
6、从数据库中导入
从数据库查询出来的数据可以直接导入到表格打印
+------+----------+----------+------------+
| 编号 | 云编号 | 名称 | IP地址 |
+------+----------+----------+------------+
| 1 | server01 | 服务器01 | 172.16.0.1 |
| 2 | server02 | 服务器02 | 172.16.0.2 |
| 3 | server03 | 服务器03 | 172.16.0.3 |
| 4 | server04 | 服务器04 | 172.16.0.4 |
| 5 | server05 | 服务器05 | 172.16.0.5 |
| 6 | server06 | 服务器06 | 172.16.0.6 |
| 7 | server07 | 服务器07 | 172.16.0.7 |
| 8 | server08 | 服务器08 | 172.16.0.8 |
| 9 | server09 | 服务器09 | 172.16.0.9 |
+------+----------+----------+------------+
7、表数据的删除
prettytable提供四种方法用于删除数据:
del_row:删除某行,允许传入一个整数参数,(从0开始)。
del_column:删除某列,允许传入一个字符串,表示要删除的列的字段名。
clear_rows:删除所有数据,但保存列的字段名。
clear:删除所有数据,包括列的字段名。
8、显示表格
get_string()
函数可以将上面print
的结果直接转化为字符串,可以将这个结果写到文本文件里。当然也可以打印出来。
9、显示指定的列
10、显示指定的行