python - 属性错误 : 'str' object has no attribute 'write'

标签 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' 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/

相关文章:

python - TensorFlow 如何安全地手动终止训练 (KeyboardInterrupt)

php - 在 Python 中解码复杂的 JSON

python - Docker:无法识别 uwsgi 服务

python - 如何使用阿里巴巴ODPS python SDK中的Schema.from_lists方法创建schema?

python - 具有类似于 Python/NumPy 的数组操作的 C++ 库

python - Discord.py:希望将 message.content 读为小写,.lower() 不起作用

python - 您将如何设置具有多个虚拟主机的 Python Web 服务器?

python - Django Fixture Loading 使用什么 JSON 解析器

python - 对文本文件的批量操作仅对一半文件执行

python - 从 argparse 获取版本字符串