简体   繁体   English

如何在python中pickle.load()之后关闭文件

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

I saved a python dictionary in this way:我以这种方式保存了一个python字典:

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:最好改用with语句,它会在语句结束时关闭文件,即使发生异常:

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.否则,文件只会在垃圾收集器运行时关闭,何时发生是不确定的,几乎无法预测。

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.使用with语句是更好的方法,但恰恰相反,如果你没有使用with ,你应该保留一个文件句柄......并从那里关闭。

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.这基本上就是with为你做的事情。

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.或者您可以使用gc模块跟踪对文件对象的引用,然后关闭它。 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有一些代码可以帮助您做到这一点,例如: 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.然而, withf.close()f.close() ,除非你真的处于泡菜中,否则你应该避免通过gc模块进行跟踪。

I guess people just want to avoid manually closing file.我猜人们只是想避免手动关闭文件。 Use pickle.loads() / dumps() and pathlib methods can do so:使用 pickle.loads() / dumps() 和 pathlib 方法可以这样做:

import pickle
import pathlib # Must be Python 3.5 or above

# one line to load pkl, auto closing file
data = pickle.loads(pathlib.Path('path/to/pkl').read_bytes())

# also one line to dump, auto closing file
pathlib.Path('path/to/save').write_bytes(pickle.dumps(data))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM