AttributeError:“ str”对象的python没有属性“ seek”

时间:2020-04-21 21:01:31

标签: python attributes attributeerror seek

在运行以下代码时,获取“ AttributeError:'str'对象没有属性'seek'”。有人可以指出问题出在哪里吗?

import re
import os
import time

regex = ' \[GC \((?<jvmGcCause>.*?)\).+?(?<jvmGcRecycletime>\d+\.\d+) secs\]'
read_line = True

def follow(thefile):
    thefile.seek(0,os.SEEK_END)
    while True:
        lines = thefile.readline()
        if not lines:
            time.sleep(0.1)
            continue
        yield lines

if __name__ == '__main__':
    logfile = r"/gc.log"
    loglines = follow(logfile)
    for line in loglines:
        match = re.search(regex, line)
        if match:
            print('jvmGcCause: ' + +match.group(1))
            print('jvmGcRecycletime: ' + match.group(2))

1 个答案:

答案 0 :(得分:5)

在python中,seek是文件对象的一种方法,您正在尝试将其应用于字符串。您必须先打开文件,然后在打开的文件对象上调用seek

执行以下操作:

def follow(file_name):
    with open filename as the_file:
        the_file.seek(0, os.SEEK_END)
        while True:
            lines = the_file.readline()
            if not lines:
                time.sleep(0.1)
                continue
            yield lines