sdrockzz sdrockzz - 2 months ago 20
Python Question

python table view output

I have some thing like this in output.txt file

Service1:Aborted
Service2:failed
Service3:failed
Service4:Aborted
Service5:failed


output in 2nd file(output2.txt) :

Service1 Service2 Servive3 Service4 Service5
Aborted failed failed Aborted failed


Would like to get output in table format as above

Code I am trying:

file=open('output.txt','r')
target=open('output2.txt','w')
states=[]
for line in file.readlines():
parts=line.strip().split(':')
states.append(parts[1].strip())
target.write(','.join(states))
target.close()

Answer

Very quickly:

headers = []
statuses = []

for line in file:
    line=line.strip()
    parts=line.split(":")
    headers.append(parts[0])
    statuses.append(parts[1])

format_str = '{:>15}'*(len(headers))

print(format_str.format(*headers))
print(format_str.format(*statuses))