Add a value to a column and print results
<p>I have a file like this</p>

<pre><code>Daniel 400 411 f
Mark 976 315 g
</code></pre>

<p>I would like to add 20 to line[2] and subtract 20 from line[1] and print new results overwriting this lines or to a new file.This is my try.</p>

<pre><code>f=open('w', 'r')
r = open('w2','a')
lines=f.readlines()
for line in lines:
  new_list = line.rstrip('\r\n').split('\t')
  q_start=int(new_list[1]) - 20
  q_end=int(new_list[2]) + 20
  # I think something is missing here, but I don't know what
  r.writelines(lines)
f.close()
r.close()
</code></pre>

<p>Expected outcome</p>

<pre><code>Daniel 380 431 f
Mark 956 335 g
</code></pre>

<p>I see that you have already accepted an answer, but still, here is my comment. There are a couple of mistakes in your code. The first is that even though you calculate the values correctly, you store them into two variable(<code>q_start</code> and <code>q_end</code>) that are not used afterwards.</p>

<p>The second mistake is that you write to the output file the unaltered original data (the <code>lines</code> list) and do so inside the loop (check your identations). hence, I believe that your output was an N repetition of the original file, where N is the number of lines in it.</p>

<p>The possible thirs mistake is using <code>'a'</code> to open the output file. If there was any content in it, it would not be deleted. Since I am not sure of your intentions, this may not be a mistake, but pay attention if you wanted a clean slate or not.</p>

<p>Finally, here is my version of your code, minimally altered to work. I left the <code>'a'</code> in the output file open process because I did not know if you did this on purpose.</p>

<pre><code>f=open('w.txt', 'r')
r = open('w2.txt','a')
lines=f.readlines()
for line in lines:
  print line  
  new_list = line.rstrip('\r\n').split(' ')
  new_list[1]=str(int(new_list[1]) - 20)
  new_list[2]=str(int(new_list[2]) + 20)  
  r.write('\t'.join(new_list)+"\n")
f.close()
r.close()
</code></pre>

<p>I hope this helps. </p>

python