Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close the file after pickle.load() in 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"))

How is it possible to close the file after this?

like image 992
user2961420 Avatar asked Nov 20 '13 16:11

user2961420


People also ask

Does pickle load close the file?

You then open the pickle file for reading, load the content into a new variable, and close up the file.

What does pickle load do in Python?

Pickle in Python is primarily used in serializing and deserializing a Python object structure. In other words, it's the process of converting a Python object into a byte stream to store it in a file/database, maintain program state across sessions, or transport data over the network.

What is pickle dump ()?

Python Pickle dump dump() function to store the object data to the file. pickle. dump() function takes 3 arguments. The first argument is the object that you want to store. The second argument is the file object you get by opening the desired file in write-binary (wb) mode.


1 Answers

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.

like image 165
Adam Rosenfield Avatar answered Sep 19 '22 12:09

Adam Rosenfield