6

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
asked Sep 25, 2015 at 10:04
1
  • the second step (reopening the file) gives the error that the file is empty Commented Sep 25, 2015 at 10:27

2 Answers 2

7

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.

answered Sep 25, 2015 at 13:22
Sign up to request clarification or add additional context in comments.

Comments

0

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)
answered Sep 25, 2015 at 10:42

1 Comment

that's weird... but yes, it works I've also tried: with open("pickletest.pickle","wb") as f: pickle.dump(messageToSend, f) with open("pickletest.pickle","rb") as g: messageReceived = pickle.load(g) and it works as well... I understood these are equivalent - apparently not. Does anyone know why?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.