Python - 以表格格式写入文件
问题描述:
我有一些使用for循环打印的变量。使用下面的函数将它们写入文件中。Python - 以表格格式写入文件
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
可以查看哪些库以获得所需的输出?
答
不需要任何外部库,使用python内置的format()函数。只是使这种更改一行:
my_file.write('{0:10} {1:14} {2:13} {3}\n'.format(str(id), nodes, svc, str(i)))
有关参数和其他可能的定制详情请参见Format Specification Mini-Language。
不需要任何库,python的内置[打印功能](https://docs.python.org/2/library/string.html#format-specification-mini-language)将很容易做到这一点。 – davedwards
如果你知道你的值的最大值,你可以使用format() –