0

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

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
13
  • You know that 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? Commented Sep 6, 2016 at 5:19
  • Yes actually it should return the current position of a file but it returns the last position. I want to print the data line by line in a file but at a time i want to print 20 lines only and next time i don't want to repeat those lines i want to print next 20 lines . So for that operation I am using f1.seek() to go to that particular position Commented Sep 6, 2016 at 5:25
  • So - are you trying to read over the file in chunks of 20 lines each? Commented Sep 6, 2016 at 5:29
  • ha yes I am trying to print 20 lines at a time Commented Sep 6, 2016 at 5:35
  • You're already loading the entire file into memory in your code so there shouldn't be a reason to want to keep file positions. You can just assign lines = f1.readlines() and then slice lines if your file is a "reasonable" size... Commented Sep 6, 2016 at 5:42

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

16 Comments

Thank u so much but How can I print those lines .First time it is ok but second time how can we go to that particular position
I have tried this but it is not coming . It only prints the first 20 lines and return the last position of a file
I think you're running your old program: my snippet doesn't print anything but the last position. added the fseek call in the end, you got that right.
hey Jean-Franscois Fabre i want to access the previous line after tell the position. That means after printing 20 i want to start printing from 20 on wards so how to do it? can u tell me please?
@surya not sure I understand. Can you rephrase?
|
0

Jean-François Fabre already explained that readline could read the whole file.

But anyway you should never mix line level input (readline) and byte level input (tell, seek or read). As the low level OS system calls can only read a byte count, readline actually reads a buffer and searches for a newline in it. But the file pointer given by tell is positionned at the end of the buffer and not at the end of the line.

There is no way to set the file pointer at the end of a line except by processing the file one char at a time and manually detecting the end of line.

1 Comment

sounds reasonable. But readline+ftell worked. The position given is the position of the 21st line as predicted. So is this luck? I'm running windows/python 3.5.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.