[英]AttributeError: 'str' object has no attribute 'write'
I'm working on Python and have defined a variable called "_headers" as shown below 我正在研究Python并定义了一个名为“_headers”的变量,如下所示
_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'" 为了将其写入输出文件,我编写了以下语句,但它引发了错误“AttributeError:'str'对象没有属性'write'”
with open(outfile, 'w') as f:
outfile.write(self._headers)
print done
Please help 请帮忙
You want f.write
, not outfile.write
... 你想要f.write
,而不是outfile.write
......
outfile
is the name of the file as a string. outfile
是文件名作为字符串。 f
is the file object. f
是文件对象。
As noted in the comments, file.write
expects a string, not a sequence. 如注释中所述, file.write
需要一个字符串,而不是序列。 If you wanted to write data from a sequence, you could use file.writelines
. 如果要从序列中写入数据,可以使用file.writelines
。 eg f.writelines(self._headers)
. 例如f.writelines(self._headers)
。 But beware, this doesn't append a newline to each line. 但要注意,这不会在每一行附加换行符。 You need to do that yourself. 你需要自己做。 :) :)
Assuming that you want 1 header per line, try this: 假设您每行需要1个标头,请尝试以下方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.