如何腌制一个物体?

发布于 2024-09-16 03:46:40 字数 420 浏览 8 评论 0原文

这是我的代码:

import pickle 

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

pickle.dump(alist, c)

这是我收到的错误:

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'

发生了什么事?我在 windows xp 上使用 python 2.4

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

掀纱窥君容 2024-09-23 03:46:40

不要将您的文件命名为 pickle.py。它与同名的 python 标准库模块冲突。所以你的 import pickle 没有获取 python 模块。

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.

如若梦似彩虹 2024-09-23 03:46:40

你的代码对我来说效果很好。

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)
>>>

问题是您的文件名“pickle.py”使 import pickle 语句尝试从您自己的文件导入而不是主库。重命名您的代码文件。

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.

紫﹏色ふ单纯 2024-09-23 03:46:40

您的脚本称为 pickle,因此隐藏了标准库中的模块 picke。它导入自身并尝试调用其 dump 函数(当然它没有)。

请注意,您很“幸运”,因为您没有陷入无限导入循环(因为导入同一模块两次只会创建对内存中同一模块对象的另一个引用)。

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文