Reputation: 332
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
Upvotes: 6
Views: 8444
Reputation: 33397
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.
Upvotes: 7
Reputation: 427
I'm not yet sure why, but the issue relates to your assigning of the variable to open the file. Don't assign the variable and the code works.
import pickle
messageToSend = ["Pickle", "this!"]
print("before: \n",messageToSend)
pickle.dump(messageToSend, open("pickletest.pickle","wb"))
messageReceived = pickle.load(open("pickletest.pickle","rb"))
print("after: \n",messageReceived)
Upvotes: 0