//
Prettytable module of python
//
The prettytable module of python allows us to format and print data records more clearly. Today, let's briefly look at the usage of this module.
Note: The package needs to be imported before use
from prettytable import PrettyTable
from prettytable import from_csv
If the corresponding python package does not exist, you need to pass:
pip install prettytable
To install it.
Method 1: directly add column names and data records
from prettytable import PrettyTable
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# Enter rows and columns directly to arrange
table =PrettyTable()
table.field_names =["Name","age","gender","height"]
table.add_row(["yeyz",26,'male',182])
table.add_row(["Ren Yingying",27,'Female',172])
table.add_row(["Yang Guo",28,'male',175])
# Add a column
table.add_column("Grades",[60,70,80])
print table
The output is as follows:
+- - - - - - - - +- - - - - - +- - - - - - +- - - - - - +- - - - +| Name|age|gender|height|Grades|+--------+------+------+------+----+| yeyz |26|male|182|60||Ren Yingying|27|Female|172|70||Yang Guo|28|male|175|80|+--------+------+------+------+----+
Process finished with exit code 0
can be seen:
The column names can be listed through field_names
The record can be added to the table through the add_row function
You can add data records to this table through add_column
Method 2: Format the output data by loading a csv file
from prettytable import PrettyTable
from prettytable import from_csv
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# Add through a file
'''
+- - - - - - - - +- - - - - - +- - - - - - +- - - - - - +- - - - - - +| Name|age|gender|height|fraction|+--------+------+------+------+------+|Andy Lau|56|male|165|30||Jacky Cheung|50|male|65|80||Jay Chou|38|male|170|90||dawn|40|male|180|100|+--------+------+------+------+------+'''
table1 =PrettyTable()
csv_file =open('csv_file.csv','r')
print csv_file
table1 =from_csv(csv_file)
print table1
The output is as follows:
+- - - - - - - - +- - - - - - +- - - - - - +- - - - - - +- - - - - - +| Name|age|gender|height|fraction|+--------+------+------+------+------+|Andy Lau|56|male|165|30||Jacky Cheung|50|male|65|80||Jay Chou|38|male|170|90||dawn|40|male|180|100|+--------+------+------+------+------+
Recommended Posts