1

我是 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'

谁能帮助我,非常感谢。

亚历克斯

4

3 回答 3

4

您必须在“filename”上调用“write”,它是 LogMessage 的一个实例,而不是在 LogMessage 类上。

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

于 2013-09-26T13:18:10.103 回答
3

如果您在使用烧瓶时遇到此类错误,请检查您的html 代码(your_form.)并将其添加到您的 html 中:

<form method="POST" action="" enctype="multipart/form-data">

enctype="multipart/form-data"会有所帮助。

于 2019-02-11T06:15:45.557 回答
0
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):
    writeInput = input('What data do you wish to write?:\n')
    outputFile = open(self.filename, 'w')
    for line in writeInput:
            print(line, file = outputFile, end='')

filename = LogMessage('new.txt')
filename.write()
filename.read()
于 2013-09-27T08:50:20.170 回答