在发现Python tabulate模块是here之后,我一直在尝试它。
当从文件中读取它时,没有单独的框,是否可以合并/加入它?
以下是示例代码和输出。
wolf@linux:~$ cat file.txt
Apples
Bananas
Cherries
wolf@linux:~$ Python代码
wolf@linux:~$ cat script.py
from tabulate import tabulate
with open(r'file.txt') as f:
for i,j in enumerate(f.read().split(), 1):
table = [[ i,j ]]
print(tabulate(table, tablefmt="grid"))
wolf@linux:~$ 输出
wolf@linux:~$ python script.py
+---+--------+
| 1 | Apples |
+---+--------+
+---+---------+
| 2 | Bananas |
+---+---------+
+---+----------+
| 3 | Cherries |
+---+----------+
wolf@linux:~$ 期望输出
wolf@linux:~$ python script.py
+---+----------+
| 1 | Apples |
+---+----------+
| 2 | Bananas |
+---+----------+
| 3 | Cherries |
+---+----------+
wolf@linux:~$ 发布于 2020-07-13 23:38:17
您应该创建一个表并打印,而不是创建3次table并每次打印:
from tabulate import tabulate
with open(r'temp.txt') as f:
table = []
for i,j in enumerate(f.read().split(), 1):
table.append([ i,j ])
print(tabulate(table, tablefmt="grid"))结果:
+---+----------+
| 1 | Apples |
+---+----------+
| 2 | Bananas |
+---+----------+
| 3 | Cherries |
+---+----------+https://stackoverflow.com/questions/62879273
复制相似问题