Vigil_wang 2022-09-08 09:54 采纳率: 50%
浏览 65
已结题

使用open()函数时提示AttributeError: 'str' object has no attribute 'filename'

使用open()函数时提示AttributeError: 'str' object has no attribute 'filename'

问题相关代码,请勿粘贴截图

gapfilling.py

class Gapfilling:
    def __init__(self, filename):
        self.filename = filename
    
    def open_file(self):
        with open(self.filename, 'r') as file_object:
            return file_object
        
    def get_items(self):
        lines = Gapfilling.open_file(self.filename).readlines()
        return lines

test = Gapfilling('GP_turbine.txt')
x = test.get_items()
print(x)

运行结果及报错内容
Traceback (most recent call last):
  File "I:\PythonProgram\QstBankCreating\main.py", line 5, in <module>
    x = test.get_items()
  File "I:\PythonProgram\QstBankCreating\gapfilling_function.py", line 10, in get_items
    lines = Gapfilling.open_file(self.filename).readlines()
  File "I:\PythonProgram\QstBankCreating\gapfilling_function.py", line 6, in open_file
    with open(self.filename, 'r') as file_object:
AttributeError: 'str' object has no attribute 'filename'

运行后提示:

我的解答思路和尝试过的方法

在类中传递一个字符串失败,实在找不出破的办法,愿解答

  • 写回答

3条回答 默认 最新

  • 梦里逆天 2022-09-08 10:10
    关注

    不应该用with好吧,就用open,可以这么写:

    
    class Gapfilling:
        def __init__(self, filename):
            self.filename = filename
    
        def open_file(self):
            file_object = open(self.filename, 'r')
            return file_object
    
        def get_items(self):
            obj = self.open_file()
            lines = obj.readlines()
            obj.close()
            return lines
    
    
    test = Gapfilling('name.txt')
    filename = test.filename
    print(test)
    print(filename)
    print(test.get_items())
    # <__main__.Gapfilling object at 0x0000028ADE5D2380>
    # name.txt
    # ['Tom']
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 9月16日
  • 已采纳回答 9月8日
  • 赞助了问题酬金10元 9月8日
  • 创建了问题 9月8日

悬赏问题

  • ¥20 ue5运行的通道视频都会有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数