How do I pickle an object?

爱⌒轻易说出口 提交于 2019-12-10 12:55:10

问题


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


回答1:


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.




回答2:


The code you have works fine for me.

Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>>
>>> alist = ['here', 'there']
>>> c = open('config.pck', 'w')
>>>
>>> pickle.dump(alist, c)
>>>

The issue is that your filename "pickle.py" is making the import pickle statement try to import from your own file instead of the main library. Rename your code file.




回答3:


Your script is called pickle and therefore shadows the module picke from the standard library. It imports itself and tries to call its dump function (and of course it doesn't have one).

Note that you're "lucky" that you don't get kicked into an infinite import loop (because importing the same module twice just creates another reference to the same module object in memory).



来源:https://stackoverflow.com/questions/3558718/how-do-i-pickle-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!