abc abc - 1 year ago 85
Python Question

Unable to load pickle file

I was previously able to load a pickle file. I saved a new file under a different name. I am unable to load either the old or the new file. Which is a bummer as it contains data which I have worked hard to scrub.

Here is the code that I use to save:

def pickleStore():
pickle.dump(store, open("...shelf3.p", "wb"))

Here is the code that I use to re-load:

def pickleLoad():
store = pickle.load(open(".../shelf3.p","rb" ) )

The created file exists, and I run pickleLoad() no errors come up, neither does any variables show in the panel variable explorer. If I try to load a non-existent file, I get a error message.

I am running spyder, python 3.5.

Any suggestions?

Answer Source

If you want to write to a module-level variable from a function, you need to use the global keyword:

store = None

def pickleLoad():
    global store
    store = pickle.load(open(".../shelf3.p","rb" ) )

...or return the value and perform the assignment from module-level code:

store = None

def pickleLoad():
    return pickle.load(open(".../shelf3.p","rb" ) )

store = pickleLoad()