Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pickle an object?

Here is the code I have:

import pickle 

alist = ['here', 'there']
c = open('config.pck', 'w')

pickle.dump(alist, c)

and this is the error I receive:

Traceback (most recent call last):
  File "C:\pickle.py", line 1, in ?
import pickle
  File "C:\pickle.py", line 6, in ?
pickle.dump(alist, c)
AttributeError: 'module' object has no attribute 'dump'

whats going on? I am using python 2.4 on windows xp

like image 533
Richard Avatar asked Aug 24 '10 16:08

Richard


People also ask

How do you pickle an object?

To pickle an object into a file, call pickle. dump(object, file) . To get just the pickled bytes, call pickle. dumps(object) .

Can any object be pickled?

What can you Pickle? Generally you can pickle any object if you can pickle every attribute of that object. Classes, functions, and methods cannot be pickled -- if you pickle an object, the object's class is not pickled, just a string that identifies what class it belongs to.

How do you make an object pickle in Python?

Once the file is opened for writing, you can use pickle. dump() , which takes two arguments: the object you want to pickle and the file to which the object has to be saved. In this case, the former will be dogs_dict , while the latter will be outfile . Don't forget to close the file with close() !

Which function is used for pickling?

Pickle allows different objects to declare how they should be pickled using the __reduce__ method. Whenever an object is pickled, the __reduce__ method defined by it gets called.


1 Answers

Don't call your file pickle.py. It conflicts with the python standard libary module of the same name. So your import pickle is not picking up the python module.

like image 109
unutbu Avatar answered Oct 24 '22 20:10

unutbu