python remove last comma
<p>I have some thing like this in output.txt file</p>

<pre><code>Service1:Aborted
Service2:failed
Service3:failed
Service4:Aborted
Service5:failed
</code></pre>

<p>output in 2nd file(output2.txt) :</p>

<pre><code> Service1        Service2   Servive3   Service4     Service5
 Aborted         failed     failed     Aborted      failed
</code></pre>

<p>Would like to remove the last comma in the line.</p>

<p>Code I am trying:</p>

<pre><code>    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()
</code></pre>

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

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

python python-2.7 python-3.x