How to close the file after pickle.load() in python

user2961420 picture user2961420 · Nov 20, 2013 · Viewed 24.7k times · Source

I saved a python dictionary in this way:

import cPickle as pickle

pickle.dump(dictname, open("filename.pkl", "wb"))

And I load it in another script in this way:

dictname = pickle.load(open("filename.pkl", "rb"))

How is it possible to close the file after this?

Answer

Adam Rosenfield picture Adam Rosenfield · Nov 20, 2013

It's better to use a with statement instead, which closes the file when the statement ends, even if an exception occurs:

with open("filename.pkl", "wb") as f:
    pickle.dump(dictname, f)
...
with open("filename.pkl", "rb") as f:
    dictname = pickle.load(f)

Otherwise, the file will only get closed when the garbage collector runs, and when that happens is indeterminate and almost impossible to predict.