Using the with
statement is the better approach, but just to be contrary, if you didn't use with
, you should retain a file handle… and close from there.
f = open('filename.pkl', 'wb')
pickle.dump(dictname, f)
f.close()
and in the other script:
f = open('filename.pkl','rb')
dictname = pickle.load(f)
f.close()
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.py
However, with
and f.close()
are much much more preferred, and you should avoid tracing through the gc
module unless you really are in a pickle.