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

use*_*260 14 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',
                )
Run Code Online (Sandbox Code Playgroud)

为了将其写入输出文件,我编写了以下语句,但它抛出错误"AttributeError:'str'对象没有属性'write'"

with open(outfile, 'w') as f:  
            outfile.write(self._headers)  
            print done
Run Code Online (Sandbox Code Playgroud)

请帮忙

mgi*_*son 24

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

outfile是作为字符串的文件的名称. f是文件对象.

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


Rob*_*obᵩ 5

假设您想要每行 1 个标头,请尝试以下操作:

with open(outfile, 'w') as f:
    f.write('\n'.join(self._headers))  
    print done
Run Code Online (Sandbox Code Playgroud)