在python中的pickle.load()之后如何关闭文件 [英] How to close the file after pickle.load() in python

查看:344
本文介绍了在python中的pickle.load()之后如何关闭文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以这种方式保存了一个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"))

此后如何关闭文件?

推荐答案

最好使用

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.

这篇关于在python中的pickle.load()之后如何关闭文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆