[英]AttributeError: 'str' object has no attribute 'write'
我正在研究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
請幫忙
你想要f.write
,而不是outfile.write
......
outfile
是文件名作為字符串。 f
是文件對象。
如注釋中所述, file.write
需要一個字符串,而不是序列。 如果要從序列中寫入數據,可以使用file.writelines
。 例如f.writelines(self._headers)
。 但要注意,這不會在每一行附加換行符。 你需要自己做。 :)
假設您每行需要1個標頭,請嘗試以下方法:
with open(outfile, 'w') as f:
f.write('\n'.join(self._headers))
print done
盡可能接近您的腳本:
>>> _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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.