2013-09-23 24 views
6

Tôi đang cố gắng tìm hiểu cách pickle và lưu một đối tượng trong python. Tuy nhiên, khi tôi sử dụng sample code bên dưới, tôi nhận được lỗi sau: io.UnsupportedOperation: read quay trở lại favorite_color = pickle.load(f_myfile). Tôi không thể tìm thấy một lời giải thích tốt về lỗi cụ thể này. Tôi đang làm gì sai và làm thế nào để sửa nó?Lỗi tẩy trong Python: io.UnsupportedOperation: đọc

import pickle # or import cPickle as pickle 

# Create dictionary, list, etc. 
favorite_color = { "lion": "yellow", "kitty": "red" } 

# Write to file 
f_myfile = open('myfile.pickle', 'wb') 
pickle.dump(favorite_color, f_myfile) 
f_myfile.close() 

# Read from file 
f_myfile = open('myfile.pickle', 'wb') 
favorite_color = pickle.load(f_myfile) # variables come out in the order you put them in 
f_myfile.close() 
+0

Đó là những gì sẽ xảy ra khi bạn sao chép và dán. – cdarke

Trả lời

16

Thay đổi:

# Read from file 
f_myfile = open('myfile.pickle', 'wb') 

tới:

f_myfile = open('myfile.pickle', 'rb') 

và bạn sẽ nhìn thấy dict obj bạn đã ngâm.

+0

Thật đáng kinh ngạc khi tôi phải sử dụng Google 'lỗi' này để khám phá tôi ngu ngốc đến mức nào. Cảm ơn! –