python-3.x pickling creates empty file
Question: 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
    


Answer: 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.

