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?
It's better to use a
with
statement instead, which closes the file when the statement ends, even if an exception occurs:Otherwise, the file will only get closed when the garbage collector runs, and when that happens is indeterminate and almost impossible to predict.
Using the
with
statement is the better approach, but just to be contrary, if you didn't usewith
, you should retain a file handle… and close from there.and in the other script:
This is essentially what
with
is doing for you.However… if you were stuck (for whatever reason), with the code you originally posted, and to answer your original question… yes, the garbage collector will close it for you at some unspecified time in the future. Or you could possibly track down a reference to the file object using the
gc
module, and then close it. There are a few codes out there that might help you do this, for example: https://github.com/uqfoundation/dill/blob/master/dill/pointers.pyHowever,
with
andf.close()
are much much more preferred, and you should avoid tracing through thegc
module unless you really are in a pickle.