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?
You then open the pickle file for reading, load the content into a new variable, and close up the file.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With