1

I have a number of variables being printed using a for loop. They are being written in a file using the below function.

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()

The output that I get is :

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

The output I desire is more tabular in nature.

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

What libraries can I look into to get a desired output ?

2
  • No need for any libraries, python's built-in print function will easily do just that. Commented Apr 5, 2017 at 1:10
  • if you know the max len of your values, you can use format() Commented Apr 5, 2017 at 1:12

1 Answer 1

3

No need for any external library, use python's built-in format() function. Just make this one-line change:

my_file.write('{0:10}  {1:14}  {2:13}   {3}\n'.format(str(id), nodes, svc, str(i)))

See the Format Specification Mini-Language for details on the parameters and other possible customization.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.