Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...