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>There's really no need to read in all the lines into memory, then loop over them. It just lengthens the code and is less efficient. Instead, try</p>

<pre><code>with open('w2','w') as out:
    for line in open('w', 'r'):
        new_list = line.rstrip('\r\n').split('\t')
        q_start=int(new_list[1]) - 20
        q_end=int(new_list[2]) + 20
        out.write('\t'.join([line[0], str(q_start), str(q_end), line[3]]) + '\n')
</code></pre>

<p>Note the use of <a href="http://stackoverflow.com/questions/9282967/how-to-open-a-file-using-the-open-with-statement"><code>with</code> to open <code>'w2'</code></a>, and the <a href="http://stackoverflow.com/questions/5733419/how-to-iterate-over-the-file-in-python">more efficient loop over the <code>'w'</code>'s lines</a>.</p>

<hr>

<p><strong>Edit Addressing Comment</strong></p>

<p>Note that if you have multiple columns (but still need to update only those at columns at 1 and 2), you can change the last line to </p>

<pre><code>        out.write('\t'.join([line[0], str(q_start), str(q_end)] + line[3: ]) + '\n')
</code></pre>

python