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

问题描述:

我想打开一个文件,并使用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 

它读取整个文件。

+1

是的,这就是'readlines'一样。你准确的问题是什么? – 2013-03-24 03:29:05

+0

我需要逐行读取,保存last_pos到某处,关闭文件,打开文件,查找last_pos,读取行,更新last_pos,关闭文件... – John 2013-03-24 03:34:28

+0

@John,if you're在子进程之间传递数据,查看StringIO等。或者考虑使用数据库,例如MySQL – smci 2016-11-29 13:45:41

OK,你可以使用这个:

f = open(...) 

f.seek(last_pos) 

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

last_pos = f.tell() 

f.close() 

只记得, last_pos不是文件中的行号,它是从文件开始的字节偏移量 - 增加/减少文件没有意义。

+1

lenik:我不知道你的答案中的文件阅读过程http://*.com/questions/15527617/read-each-line-of-a-text-file-using-cron-schedule。所以我在这里打开一个新的问题:) – John 2013-03-24 03:44:31

+0

好的,这是怎么回事。你有一个变量'last_pos',它包含文件开头的当前字节偏移量。你打开文件,'seek()'到那个偏移量,然后用'readline()'读一行。文件指针自动前进到下一行的开头。那么你可以使用tell()来获得新的偏移量并将其保存到last_pos中,以便在下一次迭代中使用。请指出这个过程的哪一部分不清楚,我会试着更详细地解释。 – lenik 2013-03-24 03:48:32

+0

它的工作原理。 thanx – John 2013-03-24 03:48:56

你有什么理由不得不使用f.tell和f.seek? Python中的文件对象是可迭代 - 这意味着你可以在一个文件中的行循环本身,而不必担心其他东西:

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

不,不,我有特殊的原因需要使用f.tell和f.seek。 – John 2013-03-24 03:32:31

+1

你会如此善意告诉我们你的特殊原因吗? – lenik 2013-03-24 03:34:09

+0

我需要在每次读取一行后关闭文件。 – John 2013-03-24 03:35:08

用于获取当前位置。当你想改变一个文件的特定行的方式:

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)