1. 程式人生 > >python write() argument must be str, not bytes

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}