Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'str' object has no attribute 'write'

Tags:

I'm working on Python and have defined a variable called "_headers" as shown below

_headers = ('id',                 'recipient_address_1',                 'recipient_address_2',                 'recipient_address_3',                 'recipient_address_4',                 'recipient_address_5',                 'recipient_address_6',                 'recipient_postcode',                 ) 

and in order to write this into an output file, I've written the following statement but it throws me the error "AttributeError: 'str' object has no attribute 'write'"

with open(outfile, 'w') as f:               outfile.write(self._headers)               print done 

Please help

like image 388
user1345260 Avatar asked Sep 09 '13 17:09

user1345260


People also ask

How do I fix AttributeError str object has no attribute?

The Python "AttributeError: 'str' object has no attribute" occurs when we try to access an attribute that doesn't exist on string objects. To solve the error, make sure the value is of the expected type before accessing the attribute.

Why am I getting AttributeError object has no attribute?

If you are getting an object that has no attribute error then the reason behind it is because your indentation is goofed, and you've mixed tabs and spaces.

How do I fix AttributeError str object has no attribute append?

The Python "AttributeError: 'str' object has no attribute 'append'" occurs when we try to call the append() method on a string (e.g. a list element at specific index). To solve the error, call the append method on the list or use the addition (+) operator if concatenating strings.

How do I fix AttributeError in Python?

Solution for AttributeError Errors and exceptions in Python can be handled using exception handling i.e. by using try and except in Python. Example: Consider the above class example, we want to do something else rather than printing the traceback Whenever an AttributeError is raised.


2 Answers

You want f.write, not outfile.write...

outfile is the name of the file as a string. f is the file object.

As noted in the comments, file.write expects a string, not a sequence. If you wanted to write data from a sequence, you could use file.writelines. e.g. f.writelines(self._headers). But beware, this doesn't append a newline to each line. You need to do that yourself. :)

like image 152
mgilson Avatar answered Sep 28 '22 20:09

mgilson


Assuming that you want 1 header per line, try this:

with open(outfile, 'w') as f:     f.write('\n'.join(self._headers))       print done 
like image 20
Robᵩ Avatar answered Sep 28 '22 20:09

Robᵩ