Python AttributeError: 'str' 对象没有属性 'write'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18703525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:31:13  来源:igfitidea点击:

AttributeError: 'str' object has no attribute 'write'

python

提问by user1345260

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' object has no attribute 'write'”

with open(outfile, 'w') as f:  
            outfile.write(self._headers)  
            print done

Please help

请帮忙

回答by mgilson

You want f.write, not outfile.write...

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

outfileis the name of the file as a string. fis the file object.

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

As noted in the comments, file.writeexpects a string, not a sequence. If you wanted to write data from a sequence, you could use file.writelines. e.g. f.writelines(self._headers). But beware, this doesn't append a newline to each line. You need to do that yourself. :)

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

回答by Rob?

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

回答by Stefan van den Akker

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