Python 读写文件 错误TypeError: write() argument must be str, not bytes+
2017-10-09 14:55
1206 查看
今天使用Python向文件中写入中文乱码,代码如下:
后来指定写入字符串的编码格式为UTF-8,出现错误TypeError: write() argument must be str, not bytes
网上搜索才发现原来是文件打开方式有问题,把之前的打开语句修改为用二进制方式打开就没有问题
完整的代码如下:
且中文不会乱码
产生问题的原因是因为pickle存储方式默认是二进制方式。
来源:http://blog.csdn.net/zengxyuyu/article/details/53038763
fo = open("temp.txt", "w+") str = '中文' fo.write(str) fo.close()
后来指定写入字符串的编码格式为UTF-8,出现错误TypeError: write() argument must be str, not bytes
fo = open("temp.txt", "w+") str = '中文' str = str.encode('utf-8') fo.write(str) fo.close()
网上搜索才发现原来是文件打开方式有问题,把之前的打开语句修改为用二进制方式打开就没有问题
fo = open("temp.txt", "wb+")
完整的代码如下:
fo = open("temp.txt", "wb+") str = '中文' str = str.encode('utf-8') fo.write(str) fo.close()
且中文不会乱码
产生问题的原因是因为pickle存储方式默认是二进制方式。
来源:http://blog.csdn.net/zengxyuyu/article/details/53038763
相关文章推荐
- 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 numpy.float64
- Python之Headers value 1 must be of type str or bytes, not <class 'int'>错误的解决
- python-rrdtool创建rrd文件的TypeError: argument 0 must be string 错误
- python write()参数错误,导致报错TypeError: a bytes-like object is required, not 'str'
- TypeError: strptime() argument 0 must be str, not class 'bytes'解决办法
- 问题记录2:TypeError: write() argument must be str, not bytes
- Python出现TypeError: file() argument 1 must be encoded string without NULL bytes, not str问题解决
- python:PyInstaller打包发布单个文件错误struct.error: argument for 's' must be a string解决
- TypeError: write() argument must be str, not bytes
- TypeError: write() argument must be str, not bytes
- Python 3.5 Socket TypeError: a bytes-like object is required, not 'str' 错误提示
- python3中,socket使用send函数时出现的错误:TypeError: a bytes-like object is required, not 'str'
- docx2txt TypeError: write() argument must be str, not bytes
- python TypeError: must be str, not bytes错误
- python3-网络编程-TypeError: send() argument 1 must be bytes or buffer, not str异常