我是 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'
谁能帮助我,非常感谢。
亚历克斯