seek()在文件处理中的问题

时间:2011-03-23 00:31:07

标签: python

我在文件中使用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 个答案:

答案 0 :(得分: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')))

对于每个文件名后跟一个错误,它返回一个包含文件名和所有后续行的字符串,最多但不包括下一个文件名或文件结尾。

答案 1 :(得分:1)

seek()更常用于随机访问文件读取。如果正在读取的文件已经是文本并且可以逐行读取,那么您只需要读取该行,然后使用字符串操作对该行进行操作。无需移动文件读取位置。

您的代码只需如下所示:

for line in f:  
    do_stuff_with line

答案 2 :(得分:0)

与stdio的fseek()类似,seek(offset [,whence])设置当前位置的偏移量。默认为0.so你可以这样做:

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