Python中出现AttributeError: 'str' object has no attribute 'seek'错误

5
在运行以下代码时出现“AttributeError: 'str' object has no attribute '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
你好,Rakesh。欢迎来到StackOverflow!你能展示完整的错误信息吗? - Nick
1个回答

9
在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

是的,那很有帮助。谢谢。 - Rakesh
很高兴能够帮到您!如果您觉得我的回答对您有用,请随意接受我的答案 - oszkar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接