Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 539
John Avatar asked Mar 24 '13 03:03

John


2 Answers

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.

like image 147
lenik Avatar answered Oct 05 '22 23:10

lenik


Is there any reason why you have to use f.tell and f.seek? The file object in Python is iterable - meaning that you can loop over a file's lines natively without having to worry about much else:

with open('test.txt','r') as file:
    for line in file:
        #work with line
like image 37
Sean Johnson Avatar answered Oct 05 '22 22:10

Sean Johnson