Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python-3.x pickling creates empty file

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
like image 562
Adam Avatar asked Sep 25 '15 10:09

Adam


People also ask

Why pickle is not good in Python?

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”.

What does pickling a file do?

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.

Does python pickle compress data?

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.


1 Answers

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.

like image 85
JBernardo Avatar answered Sep 21 '22 02:09

JBernardo