1

I'm new to Python and currently learning, I had a task to do some reading and writing to files with a python script. The reading part of my script seems to work as expected however the write section is throwing an error. It's probably something trivial I have done but here is my code:

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)

The read part works but taking user data and writing it to the file and gives this error:

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'

can anyone help me, thanks a lot.

Alex

1
  • 2
    You're not calling write() as an instance method. Maybe you meant filename.write(...) instead of LogMessage.write(...)? Commented Sep 26, 2013 at 13:17

3 Answers 3

5

If you get such errors while using flask check your html code( your_form.) and add this to your html :

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

enctype="multipart/form-data" would help.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks helped me fixed my syntax missing of form-data
4

You must call 'write' on 'filename', which is an instance of LogMessage, not on the LogMessage class.

Apart from this, there are other issues (e.g. 'writeInput' is not defined in method 'write')

Comments

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.