Python read lines from a file and write from a specific line number to another file
<p>I want to read the lines from a file and write from a specific line number to another file. I have this script, which writes all the read lines. I need to skip the first four lines and write the rest to another fils. Any ideas?</p>

<pre><code>for k in range (0,16):
    print 'k =',k
    from  abaqus import session
    k=k+1
    print k 
    f1 = open('VY_NM_VR_lin_o1_bonded_results_{k}.txt'.format(k=k))
    #with open('VY_{k}'.format(k=k), 'a') as f1:
    lines = f1.readlines()
    for i, line in enumerate(lines):
        #print i    
        print(repr(line))               
        #if line.startswith(searchquery):
        f2.write(line)
        #f2.write('%s'%listc + "\n")
        i = i+1
        #else :
        #    i = i+1
        #os.close(f1)
    f1.close()

f2.close()
</code></pre>

<p><a href="https://docs.python.org/3/library/itertools.html#itertools.islice" rel="nofollow"><code>itertools.islice</code> is designed for this</a>:</p>

<pre><code>import itertools

with open('VY_NM_VR_lin_o1_bonded_results_{k}.txt'.format(k=k)) as f1:
    # islice w/4 &amp; None skips first four lines of f1, then generates the rest,
    # and writelines can take that iterator directly to write them all out
    f2.writelines(itertools.islice(f1, 4, None))
</code></pre>

<p>If you need to process the lines as you go, then skip <code>writelines</code> and go back to:</p>

<pre><code>    for line in itertools.islice(f1, 4, None):
        ... do stuff with line ...
        f2.write(line)
</code></pre>

<p>Either way, you never even see the first four lines (Python is reading them and discarding them for you seamlessly).</p>

python file