我们可以通过add_row方法将行添加到PrettyTable对象中.
演示:
>>> from prettytable import PrettyTable
>>> import random
>>>
>>> x = PrettyTable(["ServiceID", "Service", "Price"])
>>>
>>> while True:
... #- Get value
... ID = random.randint(1,90000) #range high to lower probability of non-uniqueness
... prompt1 = raw_input("Please add a service name to the list\n")
... try:
... #- Type Casting.
... prompt2 = int(raw_input("Please enter a price for the service\n"))
... except ValueError:
... print("Please enter valid type")
... continue
... #- Add row
... x.add_row([ID, prompt1, prompt2])
... #- Ask user to Continue or not.
... choice = raw_input("Continue yes/ no:").lower()
... if not(choice=="yes" or choice=="y"):
... break
...
Please add a service name to the list
2
Please enter a price for the service
3
Continue yes/ no:y
Please add a service name to the list
4
Please enter a price for the service
6
Continue yes/ no:y
Please add a service name to the list
5
Please enter a price for the service
7
Continue yes/ no:n
>>> print x
+-----------+---------+-------+
| ServiceID | Service | Price |
+-----------+---------+-------+
| 38515 | 2 | 3 |
| 8680 | 4 | 6 |
| 51188 | 5 | 7 |
+-----------+---------+-------+
>>>
删除行:
使用del_row()方法.我们需要传递要删除的行的索引.
>>> print x
+-----------+---------+-------+
| ServiceID | Service | Price |
+-----------+---------+-------+
| 38515 | 2 | 3 |
| 8680 | 4 | 6 |
| 51188 | 5 | 7 |
+-----------+---------+-------+
>>> x.del_row(1)
>>> print x
+-----------+---------+-------+
| ServiceID | Service | Price |
+-----------+---------+-------+
| 38515 | 2 | 3 |
| 51188 | 5 | 7 |
+-----------+---------+-------+
如果我们提供的索引值大于异常中的总行数,则需要处理异常,需要在ur代码中处理.
例外情况是:
>>> x.del_row(10)
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/prettytable.py", line 832, in del_row
raise Exception("Cant delete row at index %d, table only has %d rows!" % (row_index, len(self._rows)))
Exception: Cant delete row at index 10, table only has 2 rows!
注意:
>对Python 2.x使用raw_input()>对Python 3.x使用input()