2011-03-23 62 views
0

我在文件中使用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)移动文件指针到字符#,而不是线#

回答

3

使用.tell()存储您的开始位置,然后您可以将.seek()移回原始位置。

编辑:我想这是你想要什么:

def errorsInLog(fname, newfileStr='D:', iserrorStr='error'): 
    with open(fname) as inf: 
     prev = pos = inf.tell() 
     line = inf.readline() 
     error = False 

     while line: 
      if line.startswith(newfileStr): 
       if error: 
        inf.seek(prev) 
        yield(inf.read(pos-prev)) 
       prev = pos 
       error = False 
      elif line.startswith(iserrorStr): 
       error = True 

      pos = inf.tell() 
      line = inf.readline() 

     if error: 
      inf.seek(prev) 
      yield(inf.read()) 

def main(): 
    print('\n\n'.join(errorsInLog('fileblah'))) 

对于每一个文件名,然后返回一个字符串包含文件名错误,所有后续行,直到但不包括下一个文件名或文件结束。

0

像stdio的fseek(),seek(offset [,whence])设置当前位置的偏移量。因此你可以这样做:

while(not(line.startwith("D:"))): 
     fseek(tail_position,'\n') 
     tail_position ++ 
1

seek()用在随机存取文件读取中的次数更多。如果正在读取的文件已经是文本,并且可以逐行读取,那么您只需要读取该行,然后使用字符串操作在行上进行操作。没有必要移动文件读取位置。

你的代码,只需要像这样:

for line in f: 
    do_stuff_with line