the usage of pickle

Brian McErlean brianmce at bigfoot.com
Fri Aug 10 17:23:17 CEST 2001


Dino Hsu <dino1_nospam at ms1.hinet.net> wrote in message news:<egb7nt4ba7iusumbjsd8thqhd0j943c1qf at 4ax.com>...
> Dear all,
> 
> When I try pickle.dump(...), it always fails, anyone show me how?
> Thanks in advance.
> 
> >>> def f():
>  return '123456'
> >>> f
> <function f at 01215F2C>
> 
> >>> pickle.dump(f,'test.txt')
> Traceback (most recent call last):
>   File "<pyshell#60>", line 1, in ?
>     pickle.dump(f,'test.txt')
>   File "c:\python21\lib\pickle.py", line 939, in dump
>     Pickler(file, bin).dump(object)
>   File "c:\python21\lib\pickle.py", line 104, in __init__
>     self.write = file.write
> AttributeError: write
> 
> Dino


Pickle accepts a file object as its second parameter, 
not a filename - the AttributeError is because python is trying
to find the 'write' method of the string "test.txt"

Try this instead:

>>> file = open("test.txt","w")   # Open for writing
>>> pickle.dump(f,file)
>>> file.close()

You can reload it similarly:

>>> infile = open("test.txt")
>>> obj = pickle.load(infile)
>>> obj()
'123456'

But note : Pickle does not save the bytecode for functions, just 
the name.  If you put a "del f" before the pickle.load() call, then
this will fail. (Try pickle.dumps(f) to see what the data looks
like pickled.)

-- 
Brian McErlean



More information about the Python-list mailing list