f.seek()和f.tell()读取文本文件的每一行

Joh*_*ohn 6 python file-io seek tell

我想打开一个文件并使用f.seek()和读取每一行f.tell():

的test.txt:

abc
def
ghi
jkl
Run Code Online (Sandbox Code Playgroud)

我的代码是:

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
Run Code Online (Sandbox Code Playgroud)

它读取整个文件.

len*_*nik 17

好的,你可以用这个:

f = open( ... )

f.seek(last_pos)

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

last_pos = f.tell()

f.close()
Run Code Online (Sandbox Code Playgroud)

请记住,last_pos不是文件中的行号,它是从文件开头偏移的字节 - 递增/递减它没有意义.