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

霸气de小男生 提交于 2020-01-01 02:19:39

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/20101021/how-to-close-the-file-after-pickle-load-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!