AttributeError:'str'对象没有属性'write'

时间:2013-09-09 17:16:15

标签: python

我正在使用Python并定义了一个名为“_headers”的变量,如下所示

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

并且为了将其写入输出文件,我写了以下语句,但它抛出错误“AttributeError:'str'对象没有属性'write'”

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

请帮忙

3 个答案:

答案 0 :(得分:19)

您需要f.write,而不是outfile.write ...

outfile是文件名作为字符串。 f是文件对象。

如评论中所述,file.write需要字符串,而不是序列。如果要从序列中写入数据,可以使用file.writelines。例如f.writelines(self._headers)。但要注意,这不会在每一行附加换行符。你需要自己做。 :)

答案 1 :(得分:3)

假设您每行需要1个标头,请尝试以下方法:

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

答案 2 :(得分:1)

尽可能贴近您的剧本:

>>> _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