user2819592
user2819592

Reputation:

AttributeError: 'str' object has no attribute 'filename' in Python

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

Upvotes: 1

Views: 15500

Answers (3)

Anubhav Kumar
Anubhav Kumar

Reputation: 51

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.

Upvotes: 4

user2819592
user2819592

Reputation:

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

Upvotes: 0

Don
Don

Reputation: 17606

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

Upvotes: 4

Related Questions