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.

有帮助吗?

解决方案

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.

其他提示

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

A way for getting current position When you want to change a specific line of a file:

cp = 0 # current position

with open("my_file") as infile:
    while True:
        ret = next(infile)
        cp += ret.__len__()
        if ret == string_value:
            break
print(">> Current position: ", cp)

Skipping lines using islice works perfectly for me and looks like is closer to what you're looking for (jumping to a specific line in the file):

from itertools import islice

with open('test.txt','r') as f:
    f = islice(f, last_pos, None)
    for line in f:
        #work with line

Where last_pos is the line you stopped reading the last time. It will start the iteration one line after last_pos.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top