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

Python f、 seek()和f.tell()读取文本文件的每一行,python,file-io,seek,tell,Python,File Io,Seek,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 te

我想打开一个文件并使用
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.tell和f.seek吗?Python中的file对象是iterable的,这意味着您可以在本地循环文件行,而无需担心其他问题:

with open('test.txt','r') as file:
    for line in file:
        #work with line
好的,你可以用这个:

f = open( ... )

f.seek(last_pos)

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

last_pos = f.tell()

f.close()

请记住,
last\u pos
不是文件中的行号,它是从文件开头开始的字节偏移量——增加/减少它没有意义。

当您要更改文件的特定行时,获取当前位置的一种方法:

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)

使用islice跳过行非常适合我,看起来更接近您要查找的内容(跳到文件中的特定行):

从itertools导入islice
以open('test.txt','r')作为f:
f=islice(f,最后位置,无)
对于f中的行:
#用线工作

其中last_pos是您上次停止阅读的行。它将在最后一个位置后一行开始迭代。

是的,
readlines
就是这样做的。你的问题到底是什么?我需要逐行阅读,保存LaSTPOS,关闭文件,打开文件,查找LaSTPoPs,读行,更新LaSTPOS,关闭文件…@约翰,如果你在子进程之间传递数据,查看StRIGIO等,或者考虑使用一个数据库,例如MySqLNO,我有特殊的原因需要使用f.tell和f.seek。您能告诉我们您的特殊原因吗?@John-为什么每次都需要关闭文件?另一个原因可能是需要保留当前到达的位置,以便以后能够继续阅读(例如,假设您正在编写日志解析器)lenik:我不明白你的回答中的文件读取过程。所以我在这里提出了一个新问题:)好的,事情是这样的。您有一个变量
last_pos
,它包含从文件开头开始的当前字节偏移量。打开文件,
seek()
到该偏移量,然后使用
readline()
读取一行。文件指针自动前进到下一行的开头。然后使用
tell()
获取新的偏移量,并将其保存到
last\u pos
以在下一次迭代中使用。请指出此过程的哪一部分不清楚,我将尝试详细解释。不客气!=)对不起,我一开始没解释清楚time@lenik
readlines
中的“s”不是一个打字错误,它是另一个实现的方法()关于这个方法的一篇很棒的博文:但是我如何才能获得最后的位置呢?