使用f.seek()和f.tell()逐行读取文本文件

10 投票
4 回答
65741 浏览
提问于 2025-04-17 20:06

我想打开一个文件,然后用 f.seek()f.tell() 来逐行读取内容:

文件内容是:

abc
def
ghi
jkl

我的代码是:

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

但是它读取了整个文件。

4 个回答

0

当你想要修改文件中的某一特定行时,获取当前的位置的方法:

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)
2

你有没有想过为什么要用 f.tell 和 f.seek 这两个方法?其实在 Python 中,文件对象是可以被遍历的,也就是说你可以直接循环读取文件的每一行,而不需要考虑太多其他的事情:

with open('test.txt','r') as file:
    for line in file:
        #work with line
20

好的,你可以使用这个:

f = open( ... )

f.seek(last_pos)

line = f.readline()  # no 's' at the end of `readline()`

last_pos = f.tell()

f.close()

只要记住,last_pos 不是你文件中的行号,而是从文件开始到这个位置的字节数 -- 所以没有必要去增加或减少它。

撰写回答