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>This makes the output you originally requested:</p>

<pre><code>file=open('output.txt','r')
target=open('output2.txt','w')
states = [line.strip().split(':')[-1] for line in file.readlines()]
target.write(','.join(states))
target.close()
</code></pre>

<p>That is, the output of this code is:</p>

<pre><code>Aborted,failed,failed,Aborted,failed
</code></pre>

<p>For a table view, assuming the tabbed output will line up, this code:</p>

<pre><code>file=open('output.txt','r')
target=open('output2.txt','w')
states, titles = [], []
for line in file.readlines():
    title, state = line.split(':')
    titles.append(title)
    states.append(state)
target.write('\t'.join(titles))
target.write('\n')
target.write('\t'.join(states))
target.close()
</code></pre>

<p>will produce the requested table view (note there are no commas in this output):</p>

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

<p>If you want to control alignment more precisely, you'll need to apply formatting, such as measuring the maximum width of text in each column and then using that as a formatting specifier.</p>

python python-2.7 python-3.x