Writing lines from input file to output file based on the order in a list
<p>I have an input data <code>input.dat</code> that looks like this:</p>

<pre><code>0.00    0.00
0.00    0.00
0.00    0.00
-0.28   1.39
-0.49   1.24
-0.57   1.65
-0.61   2.11
-0.90   1.73
-0.87   2.29
</code></pre>

<p>I have have a list denoting line numbers as follows:</p>

<pre><code>linenum = [7, 2, 6]
</code></pre>

<p>I need to write to a file <code>output_veloc_max.dat</code> the rows in <code>input.dat</code> that correspond to <code>linenum</code> values in the same order.</p>

<p>The result should look like this:</p>

<pre><code>-0.61 2.11
0.00 0.00 
-0.57 1.65
</code></pre>

<p>I have written the following code:</p>

<pre><code>linenum=[7,2,6]
i=1

with open('inputv.dat', 'r') as f5, open('output_veloc_max.dat', 'w') as out:
    for line1 in f5:
        if i in linenum:
            print(line1,  end=' ', file=out)
            print(i,line1)
        i+=1
</code></pre>

<p>But, it gives me output that looks like this:</p>

<pre><code>2 0.00  0.00
6 -0.57 1.65
7 -0.61 2.11
</code></pre>

<p>What am I doing wrong?</p>

<p>Store the values as you encounter them in a dictionary <code>d</code> with the keys denoting the line number and the value holding the line contents. Write them to the file with <code>writelines</code> according to the order of <code>linenum</code>. Use <code>enumerate(fileobj, 1)</code> to get a line number for each line instead of an explicit counter like <code>i</code>:</p>

<pre><code>linenum=[7,2,6]
d = {}

with open('inputv.dat', 'r') as f5, open('output_veloc_max.dat', 'w') as out:
    for num, line1 in enumerate(f5, 1):
        if num in linenum:
            d[num] = line1
    out.writelines([d[i] for i in linenum])
</code></pre>

<p>Of course, you can further trim this down with a dictionary comprehension:</p>

<pre><code>linenum = [7, 2, 6]
with open('inputv.dat', 'r') as f5, open('output_veloc_max.dat', 'w') as out:
    d = {k: v for k, v in enumerate(f5, 1) if k in linenum}
    out.writelines([d[i] for i in linenum])
</code></pre>

python python-3.x for-loop