I'm new to python, trying to store/retrieve some complex data structures into files, and am experimenting with pickling. The below example, however, keeps creating a blank file (nothing is stored there), and I run into an error in the second step. I've been googling around, only to find other examples which were exactly matching mine - yet, it does not appear to be working. What may I be missing? tx in advance!
import pickle
messageToSend = ["Pickle", "this!"]
print("before: \n",messageToSend)
f = open("pickletest.pickle","wb")
pickle.dump(messageToSend,f)
f.close
g = open("pickletest.pickle","rb")
messageReceived = pickle.load(g)
print("after: \n",messageReceived)
g.close
Pickle constructs arbitrary Python objects by invoking arbitrary functions, that's why it is not secure. However, this enables it to serialise almost any Python object that JSON and other serialising methods will not do. Unpickling an object usually requires no “boilerplates”.
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.
Pickled files are Python-version-specific — You might encounter issues when saving files in one Python version and reading them in the other. Try to work in identical Python versions, if possible. Pickling doesn't compress data — Pickling an object won't compress it.
You are not closing the files. Note you wrote f.close
instead of f.close()
The proper way to handle files in python is:
with open("pickletest.pickle", "wb") as f:
pickle.dump(messageToSend, f)
So it will close the file automatically when the with
block ends even if there was an error during processing.
The other answer given will work only in some Python implementations because it relies on the garbage collector closing the file. This is quite unreliable and error prone. Always use with
when handling anything that requires to be closed.
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