我使用for循环打印了许多变量。它们是使用以下函数写入文件的。
def writeToServiceFile(file,svc,nodes,idd,i):
my_file=open(file,"a")
my_file.write(str(id)+"\t"+nodes+"\t"+svc+"\t"+str(i)+"\n")
my_file.close()
我得到的输出是:
1000078201 172.29.219.105 kubelet None
1000078202 172.29.219.104 kubelet None
1000078204 172.29.219.103 kubelet None
1000078209 172.29.219.106 mongod SECONDARY
1000078209 172.29.219.106 elasticsearch Secondary
1000078211 172.29.219.107 mongod SECONDARY
1000078211 172.29.219.107 elasticsearch Secondary
1000078206 172.29.219.109 postgres None
1000078205 172.29.219.16 redis-server slave
1000078837 172.29.219.15 redis-server master
我想要的输出本质上更具表格性。
1000078201 172.29.219.105 kubelet None
1000078202 172.29.219.104 kubelet None
1000078204 172.29.219.103 kubelet None
1000078209 172.29.219.106 mongod SECONDARY
1000078209 172.29.219.106 elasticsearch Secondary
1000078211 172.29.219.107 mongod SECONDARY
1000078211 172.29.219.107 elasticsearch Secondary
1000078206 172.29.219.109 postgres None
1000078205 172.29.219.16 redis-server slave
1000078837 172.29.219.15 redis-server master
我可以查看哪些库以获得所需的输出?
答案 0 :(得分:1)
不需要任何外部库,使用python的内置format()函数。只需进行一行更改:
my_file.write('{0:10} {1:14} {2:13} {3}\n'.format(str(id), nodes, svc, str(i)))
有关参数和其他可能的自定义的详细信息,请参阅Format Specification Mini-Language。