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

2020-03-19 03:23发布

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.

4条回答
Evening l夕情丶
2楼-- · 2020-03-19 04:06

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2020-03-19 04:13

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.

查看更多
姐就是有狂的资本
4楼-- · 2020-03-19 04:14

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)
查看更多
趁早两清
5楼-- · 2020-03-19 04:20

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
查看更多
登录 后发表回答