Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

python - Unable to load pickle object from file

I'm just trying out the pickle module and learning its functions and utilities. I've written this small piece of code, but it's giving me trouble.

import pickle
myfile = open("C:\Users\The Folder\databin.txt", 'r+') #databin.txt is completely blank
class A:
    def __init__ (self):
        self.variable = 25
        self.random = 55
pickle.dump (A, myfile, -1) #HIGHEST_PROTOCOL 
pickle.load (myfile)

I then get the following error:

 Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
pickle.load (myfile)
File "C:Python27libpickle.py", line 1378, in load
return Unpickler(file).load()
File "C:Python27libpickle.py", line 858, in load
dispatch[key](self)
KeyError: 'x00'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'd need to close the file first, then reopen it for that to work; and use binary mode to open your file.

Last but not least, pickle can store instances of classes only, not the classes themselves:

filename = "C:\Users\The Folder\databin.txt"
with open(filename, 'wb') as myfile:
    pickle.dump(A(), myfile, -1) #HIGHEST_PROTOCOL 
with open(filename, 'rb') as myfile:
    pickle.load(myfile)

Here I've used the file as a context manager, it'll close automatically when the with suite is exited.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...