f.seek()和f.tell()读取文本文件的每一行
问题内容:
我想打开一个文件并使用f.seek()
和读取每一行f.tell()
:
test.txt:
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
它读取整个文件。
问题答案:
好的,您可以使用以下方法:
f = open( ... )
f.seek(last_pos)
line = f.readline() # no 's' at the end of `readline()`
last_pos = f.tell()
f.close()
请记住,last_pos
这不是文件中的行号,它是文件开头的一个字节偏移量–递增/递减它没有意义。