Attributeerror: 'Str' Object Has No Attribute 'Write'

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

2

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. :)

5

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

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

To stay as close to your script as possible:

>>> _headers = ('id',
...             'recipient_address_1',
...             'recipient_address_2',
...             'recipient_address_3',
...             'recipient_address_4',
...             'recipient_address_5',
...             'recipient_address_6',
...             'recipient_postcode',
...            )
>>> done = "Operation successfully completed"
>>> with open('outfile', 'w') as f:
...     for line in _headers:
...         f.write(line + "\n")
...     print done
Operation successfully completed
Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest