【问题标题】:AttributeError: 'str' object has no attribute 'seek' with pythonAttributeError:'str'对象没有属性'seek'与python
【发布时间】:2020-04-21 21:01:31
【问题描述】:

在运行以下代码时获取“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))

【问题讨论】:

  • 嗨,拉克什。欢迎来到 StackOverflow!你能显示完整的错误信息吗?

标签: python attributes attributeerror seek


【解决方案1】:

在 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

【讨论】:

  • 是的,这有帮助。谢谢
  • 很高兴能帮上忙!如果您觉得对您有用,请随时 accept my answer
猜你喜欢
  • 1970-01-01
  • 2021-05-24
  • 2021-11-24
  • 1970-01-01
  • 2018-12-01
  • 2015-09-30
  • 2021-10-22
  • 2020-09-22
  • 2020-06-25
相关资源
最近更新 更多