Search code examples
pythonpickledata-dictionary

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


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?


Solution

  • 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.