python 3.5 报错TypeError:can't concat str to bytes 、TypeError: write() argument must be str, not bytes
2018-07-05 20:28
1881 查看
原程序:
out = open('train_data.txt', 'w') for sentence in sentences: out.write(sentence.encode("utf-8")+"\n") print("done!")
报错:TypeError:can't concat str to bytes
修改为:
out.write(sentence.encode("utf-8")+b"\n")此错误消失,原因:encode返回的是bytes型的数据,不可以和str相加,将‘\n’前加b
新的错误:TypeError: write() argument must be str, not bytes
修改为:
out.write(str(sentence.encode("utf-8")+b"\n"))原因:write函数参数需要为str类型,需转化为str
后续:
发现写入的中文文本格式是:\xc2\xa0\n\xef\xbc\x88\xe8\x8b\xb1\xe5\x9b\xbd\xe5\x8f\x91\xe9\x9f\xb3\xef\xbc\x
修改程序为:
out = open('train_data.txt', 'w',encoding='utf-8') for sentence in sentences: out.write(sentence+"\n") print("done!")所有错误消失!
原因:
在windows下面,新文件的默认编码是gbk,python解释器会用gbk编码去解析我们的网络数据流txt,然而txt此时已经是decode过的unicode编码,这样的话就会导致解析不了,解决的办法就是,改变目标文件的编码:
参考:
https://www.geek-share.com/detail/2732101218.html
https://stackoverflow.com/questions/40740150/python-3-cant-concat-bytes-to-str-for-a-list
相关文章推荐
- Python 读写文件 中文乱码 错误TypeError: write() argument must be str, not bytes+
- Python 读写文件 中文乱码 错误TypeError: write() argument must be str, not bytes+
- Python 读写文件 错误TypeError: write() argument must be str, not bytes+
- python提示错误TypeError: write() argument must be str, not bytes
- Python错误TypeError: write() argument must be str, not bytes
- Python错误TypeError: write() argument must be str, not bytes
- TypeError: write() argument must be str, not bytes
- python-TypeError: write() argument must be str, not numpy.float64
- docx2txt TypeError: write() argument must be str, not bytes
- TypeError: write() argument must be str, not bytes
- 问题记录2:TypeError: write() argument must be str, not bytes
- 关于TypeError: strptime() argument 1 must be str, not bytes解析
- python TypeError: must be str, not bytes错误
- Python出现TypeError: file() argument 1 must be encoded string without NULL bytes, not str问题解决
- python3-网络编程-TypeError: send() argument 1 must be bytes or buffer, not str异常
- python错误: TypeError: the JSON object must be str, bytes or bytearray, not 'dict'解决办法
- TypeError: strptime() argument 0 must be str, not class 'bytes'解决办法
- python爬虫错误 之 write() argument must be str, not bytes
- Python持久化时抛出异常:TypeError: must be str, not bytes
- python 3.5: TypeError: a bytes-like object is required, not 'str' when writing to a file