python write() argument must be str, not bytes
程序员文章站
2024-02-21 23:17:52
...
python pickle
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pickle
dic = {
"key" : "111",
"id" : "222",
"value" : 333,
"name" : "nihao",
"age" : 18,
}
file_object = open('./test.pkl', 'w')
pickle.dump(dic,file_object,0)
file_object = open('./test.pkl', 'r')
obj = pickle.load(file_object)
print(obj)
在python2环境中,可以成功写入文件,并且可以读取文件.
输出
{'key': '111', 'age': 18, 'id': '222', 'value': 333, 'name': 'nihao'}
同样的代码在python3环境中就不能够写入成功读取成功
在python3中的输出
Traceback (most recent call last):
File "pktest.py", line 26, in <module>
pickle.dump(dic,file_object,0)
TypeError: write() argument must be str, not bytes
如果想在python3中运行相同的代码
需要在代码读取文件处type加b
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pickle
dic = {
"key" : "111",
"id" : "222",
"value" : 333,
"name" : "nihao",
"age" : 18,
}
file_object = open('./test.pkl', 'wb')
pickle.dump(dic,file_object,0)
file_object = open('./test.pkl', 'rb')
obj = pickle.load(file_object)
print(obj)
这份代码可以在python2和python3都输出
{'id': '222', 'value': 333, 'name': 'nihao', 'key': '111', 'age': 18}
上一篇: 为什么需要MyBatis?
下一篇: 如何将canvas设置为背景
推荐阅读
-
python write() argument must be str, not bytes
-
TypeError: write() argument must be str, not bytes
-
TypeError: write() argument must be str, not bytes
-
[Python] TypeError: write() argument must be str, not bytes
-
浅析Python 3 字符串中的 STR 和 Bytes 有什么区别
-
pytorch gpu版本安装外部库报错 TypeError: LoadLibrary() argument 1 must be str, not None
-
浅析Python3中的bytes和str类型
-
Python3中的bytes和str类型详解
-
Python3中内置类型bytes和str用法及byte和string之间各种编码转换 问题
-
Python3中bytes类型转换为str类型