当我腌制一个字典时,Python pickling 返回一个字符串?

发布于 2024-10-19 17:20:01 字数 593 浏览 3 评论 0原文

我目前正在学习Python中的pickle,我对一个错误感到困惑,我抱怨我正在初始化的unpickled变量没有我想要使用的特定属性。

我正在腌制脚本数据的字典,然后尝试使用以下代码unpickle.load将其返回:

def loadData():
    global script_data_filepath
    with open(script_data_filepath) as script_data_file:
        data_to_load = pickle.load(script_data_file)
        for data_item in data_to_load.items():
            print(data_item[0])
            print(data_item[1])

问题是Python说items()是不是 data_to_load 的属性,因为 data_to_load 的类型为“str”。在我给出的代码中,这是第一次声明 data_to_load ,我认为它将动态地采用分配给它的任何类型(应该是一个字典,因为我知道将从该文件加载它)。

I'm currently learning about pickling in Python and I'm confused with an error I'm getting complaing that the unpickled variable I'm initalizing does not have a particular attribute I'm wanting to use.

I'm pickling a dictionary of the script's data and then trying to unpickle.load it back using the following code:

def loadData():
    global script_data_filepath
    with open(script_data_filepath) as script_data_file:
        data_to_load = pickle.load(script_data_file)
        for data_item in data_to_load.items():
            print(data_item[0])
            print(data_item[1])

The problem is that Python is saying that items() is not an attribute of data_to_load because data_to_load is of type 'str'. In the code I've given this is the first time that data_to_load is declared, I pressumed that it would dynamically take whatever type is assigned to it (which should be a dictionary as that's what I know will be loaded from this file).

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

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

发布评论

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

评论(1

感性 2024-10-26 17:20:01

那应该有效。您发布的代码没问题。你怎么扔掉它?您使用的是 pickle.dump,而不是 pickle.dumps 作为字符串?您的问题几乎肯定出在转储代码中。

>>> import cPickle
>>> foo = {4:2}
>>> cPickle.dump(foo, open('foo.pickle', 'wb'))
>>> data_to_load = cPickle.load(open('foo.pickle'))
>>> data_to_load.items()
[(4, 2)]

That should work. The code you posted is fine. How are you dumping it? You're using pickle.dump, not pickle.dumps for a string? Your problem is almost certainly in the dumping code.

>>> import cPickle
>>> foo = {4:2}
>>> cPickle.dump(foo, open('foo.pickle', 'wb'))
>>> data_to_load = cPickle.load(open('foo.pickle'))
>>> data_to_load.items()
[(4, 2)]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文