sdrockzz sdrockzz - 2 months ago 11
Python Question

python remove last comma

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

Aborted,failed,failed,Aborted,failed,


Would like to remove the last comma in the line.

Code I am trying:

file=open('output.txt','r')
target=open('output2.txt','w')
for line in file.readlines():
line=line.strip()
parts=line.split(":")
for part in parts:
var2=part.strip()+","
target.write(var2.rstrip(',')) # Not working
target.close()

Answer

Use a list and append the items to it. Accessing parts[-1] returns the last item from the splitted parts. Then use join() to put the commas in between all collected states:

states = []
for line in file.readlines():
    parts=line.strip().split(':')
    states.append(parts.parts[-1])
print(','.join(states))