我在文件中使用seek - 文件中有一堆文件名和文件上的一些進程日誌 - 其中一些日誌有錯誤。我一行一行,如果我得到一個錯誤,我想記錄兩個文件名之間的所有內容。seek()在文件處理中的問題
當我使用seek時,我認爲不是將它移動到我想要的行,而是將它移動到字符#。例如
f=open("fileblah",'r')
while f:
line=f.readline()
counter=counter+1
f.seek(tail_position) # i want the next loop to start from after the error happened.
if line.startswith("D:")
header_position=counter
error_flag=0 #unset error flag
if line.startswith("error")
error_flag=1 #set error_flag
while(not(line.startswith("D:"): #go until next file beginning
line=f.readline()
counter=counter+1
tail_position=counter #have come to the next filename
我可以看到這是非常低效的,但它並沒有在所有的工作,因爲f.seek(tail_position)移動文件指針到字符#,而不是線#