How to get the specific number of lines in a file using python programming?
<p>This is my code for getting 20 lines every time but f1.tell() gives last position of the file. So i cannot get 20 lines for the next time.
Can anyone help me to do this? please</p>

<pre><code>f1=open("sample.txt","r")
last_pos=0
while true:
    f1.seek(last_pos)
    for line,i in enumerate(f1.readlines()):
        if line == 20:
            last_pos=f1.tell()
            break
        else:
            print i
sample.txt file contains below data
1
2
3
4
.
.
.
.
40
I want Output like
1
2
3
4
.
.
.
20
20
21
22
23
24
25
.
.
.
.
39
39
40
</code></pre>

<p>Using <code>readlines</code> reads all the file: you reach the end, hence what you are experiencing.</p>

<p>Using a loop with <code>readline</code> works, though, and gives you the position of the end of the 20th line (well, rather the start of the 21st)</p>

<p>Code (I removed the infinite loop BTW):</p>

<pre><code>f1=open("sample.txt","r")
last_pos=0
line=0
while True:
    l=f1.readline()
    if l=="":
        break
    line+=1
    if line == 20:
        last_pos=f1.tell()
        print(last_pos)
        break
f1.close()
</code></pre>

<p>You could iterate with <code>for i,l in enumerate(f1):</code> but iterators &amp; ftell are not compatible (you get: <code>OSError: telling position disabled by next() call</code>).</p>

<p>Then, to seek to a given position, just <code>f1.seek(last_pos)</code></p>

<p>EDIT: if you need to print the line twice eveny 20 lines, you actually don't even need <code>seek</code>, just print the last line when you count 20 lines.</p>

<p>BUT if you really want to do that this way, here's the way:</p>

<pre><code>f1=open("sample.txt","r")
line=0
rew=False

while True:
    start_line_pos=f1.tell()
    l=f1.readline()
    if l=="":
        break
    print(l.strip())
    line+=1
    if rew:
        rew = False   # avoid re-printing the 20th line again and again
    elif line % 20 == 0:
        f1.seek(start_line_pos)
        rew = True
        line-=1   # pre-correct line counter
f1.close()
</code></pre>

<p>You notice a bit of logic to avoid getting stuck on line 20. It works fine: when reaching line 20, 40, ... it seeks back to the previously stored file position and reads 1 line again. The <code>rew</code> flag prevents to do that more than once.</p>

python file