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

a 夏天 提交于 2019-12-19 07:29:22

问题


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.


回答1:


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.




回答2:


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



回答3:


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)



回答4:


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.



来源:https://stackoverflow.com/questions/15594817/f-seek-and-f-tell-to-read-each-line-of-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!