您的位置:首页 > 编程语言 > Python开发

Python 读写文件 错误TypeError: write() argument must be str, not bytes+

2017-10-09 14:55 1206 查看
今天使用Python向文件中写入中文乱码,代码如下:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐