how do you use pickle?

Fredrik Lundh fredrik at pythonware.com
Tue Apr 4 11:43:43 EDT 2006


John Salerno wrote:

> Here's what I have:
>
> import pickle
>
> data = open(r'C:\pickle_data.txt', 'w')
> image = open(r'C:\peakhell.jpg')
> pickle.Pickler(data)
> data.dump(image)
> data.close()
> image.close()
>
> First off, I'm not sure the second line is the way to do that. But my
> main problem is I don't know how to define the steps when pickling an
> object. How do you first create the object? Does it return a value? I tried:
>
> pickler = pickle.Pickler(data)
> pickle.Pickler(data)
>
> Then I tried:
>
> pickler.dump(image)
> data.dump(image)
>
> Basically, I'm just confused about all the syntax involved. Which
> objects do I operate on

any object that supports pickling.

file handles does not belong to that group (what did you expect
pickle to do with a file handle ?)

or did "object" refer to the Pickler instance?  you don't really need to
bother with that; just use the dump *function* instead:

    pickle.dump(object, file)

but if you insist on using your own Pickler instance, you have to save
the pickler instance in a variable, and call the dump method on that in-
stance:

    myfile = open(somefilename, "wb")
    mypickler = pickle.Pickler(myfile)
    mypickler.dump(object)

</F>






More information about the Python-list mailing list