26

我正在使用 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

请帮忙

4

3 回答 3

29

你想要f.write,而不是outfile.write...

outfile是字符串形式的文件名。 f是文件对象。

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

于 2013-09-09T17:17:26.793 回答
4

假设您希望每行有 1 个标题,请尝试以下操作:

with open(outfile, 'w') as f:
    f.write('\n'.join(self._headers))  
    print done
于 2013-09-09T17:23:33.067 回答
2

要尽可能接近您的脚本:

>>> _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
于 2013-09-09T19:28:47.503 回答