Skip to main content
 首页 » 编程设计

python之属性错误 : 'str' object has no attribute 'filename' in Python

2025年05月04日18softidea

我是 Python 的新手,目前正在学习,我的任务是使用 Python 脚本对文件进行一些读写操作。我脚本的读取部分似乎按预期工作,但写入部分抛出错误。这可能是我所做的微不足道的事情,但这是我的代码:

class LogMessage(): 
  def __init__(self, filename): 
    self.filename = filename 
 
  def read(self): 
    inputFile = open(self.filename) 
    for line in inputFile: 
        print(line, end='') 
 
  def write(self): 
    outputFile = open(self.filename) 
    #writeInput = input('What data do you wish to write?:\n') 
    for line in writeInput: 
            print(line,file = outputFile, end='') 
 
 
 
 
filename = LogMessage('new.txt') 
filename.read() 
writeInput = input('What data do you wish to write?:\n') 
LogMessage.write(writeInput) 

读取部分工作但获取用户数据并将其写入文件并给出此错误:

Traceback (most recent call last): 
File "/home/alex/workspace/Python/Learn Python/labEx9.py", line 22, in <module> 
LogMessage.write(writeInput) 
File "/home/alex/workspace/Python/Learn Python/labEx9.py", line 11, in write 
outputFile = open(self.filename) 
AttributeError: 'str' object has no attribute 'filename' 

谁能帮帮我,非常感谢。

亚历克斯

请您参考如下方法:

您必须在“文件名”上调用“写入”,它是 LogMessage 的一个实例,而不是在 LogMessage 类上。

除此之外,还有其他问题(例如,“writeInput”未在方法“write”中定义)