Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 类型错误:can';t concat bytes to str,那么,TypeError:write()参数必须是str,而不是bytes_Python - Fatal编程技术网

Python 类型错误:can';t concat bytes to str,那么,TypeError:write()参数必须是str,而不是bytes

Python 类型错误:can';t concat bytes to str,那么,TypeError:write()参数必须是str,而不是bytes,python,Python,最近在学习Python,我正在尝试做一个小练习。然后这个错误就出现了 File "/Users/Alexis/.spyder-py3/temp.py", line 29, in <module> f.write(txt+'\n') TypeError: can't concat bytes to str 我试过几种不同的方法 我试过了 f.write(txt+'\n'.encode('ascii')) TypeError: write() argument must

最近在学习Python,我正在尝试做一个小练习。然后这个错误就出现了

  File "/Users/Alexis/.spyder-py3/temp.py", line 29, in <module>
    f.write(txt+'\n')

TypeError: can't concat bytes to str
我试过几种不同的方法

我试过了

f.write(txt+'\n'.encode('ascii'))

TypeError: write() argument must be str, not bytes
f.write(txt+'\n'.encode('utf-8'))

TypeError: write() argument must be str, not bytes
TypeError: write() argument must be str, not bytes
谢谢你的帮助

试试这个:
f.write(str(txt)+'\n',utf-8')#或者您正在编码的任何方式

从错误消息中,
write()
需要一个字符串,但您给它的是字节,因此,必须调用
str()
将txt转换为str类型。

尝试以下操作。
f、 写入(txt.decode()+'\n')

为什么要将
i.text
编码到UTF-8?如果您不编码
txt
,它将是一个
str
对象,您可以很好地连接更多文本,并将其写入您的文本文件而无需再次解码。请详细说明一下?你为什么认为这是解决办法?我为我的简短道歉!这个解释够了吗@MatthiasThis解释了如何消除错误,但问题的主要原因是,
txt
以前编码为UTF-8,没有任何原因。现在它说,TypeError:write()只接受一个参数(给定2个)
f.write(txt+'\n'.encode('ascii'))

TypeError: write() argument must be str, not bytes
f.write(txt+'\n'.encode('utf-8'))

TypeError: write() argument must be str, not bytes
TypeError: write() argument must be str, not bytes