python write() argument must be str, not bytes

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}

转载于:https://www.cnblogs.com/vercont/p/10210166.html

你可能感兴趣的:(python write() argument must be str, not bytes)