pythonfile-ioseektell

f.seek() and f.tell() to read each line of text file


I want to open a file and read each line using f.seek() and f.tell():

test.txt:

abc
def
ghi
jkl

My code is:

f = open('test.txt', 'r')
last_pos = f.tell()  # get to know the current position in the file
last_pos = last_pos + 1
f.seek(last_pos)  # to change the current position in a file
text= f.readlines(last_pos)
print text

It reads the whole file.


Solution

  • ok, you may use this:

    f = open( ... )
    
    f.seek(last_pos)
    
    line = f.readline()  # no 's' at the end of `readline()`
    
    last_pos = f.tell()
    
    f.close()
    

    just remember, last_pos is not a line number in your file, it's a byte offset from the beginning of the file -- there's no point in incrementing/decrementing it.