Using readlines reads all the file: you reach the end, hence what you are experiencing.
Using a loop with readline works, though, and gives you the position of the end of the 20th line (well, rather the start of the 21st)
Code (I removed the infinite loop BTW):
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()
You could iterate with for i,l in enumerate(f1): but iterators & ftell are not compatible (you get: OSError: telling position disabled by next() call).
Then, to seek to a given position, just f1.seek(last_pos)
EDIT: if you need to print the line twice eveny 20 lines, you actually don't even need seek, just print the last line when you count 20 lines.
BUT if you really want to do that this way, here's the way:
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()
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 rew flag prevents to do that more than once.
f.tell()returns the position of the file pointer in the file - it's not got anything to do with the number of lines? Are you trying to count the number of lines (as per your title suggests) in a file or do something else?lines = f1.readlines()and then slicelinesif your file is a "reasonable" size...