我正在使用 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' object has no attribute 'write'”
with open(outfile, 'w') as f:
outfile.write(self._headers)
print done
请帮忙
最佳答案
你想要f.write
,而不是outfile.write
...
outfile
是字符串形式的文件名。 f
是文件对象。
如评论中所述,file.write
需要一个字符串,而不是一个序列。如果你想从一个序列中写入数据,你可以使用 file.writelines
。例如f.writelines(self._headers)
。但请注意,这不会在每一行后附加一个换行符。你需要自己做。 :)
关于python - 属性错误 : 'str' object has no attribute 'write' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18703525/