当我腌制一个字典时,Python pickling 返回一个字符串?
我目前正在学习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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那应该有效。您发布的代码没问题。你怎么扔掉它?您使用的是
pickle.dump
,而不是pickle.dumps
作为字符串?您的问题几乎肯定出在转储代码中。That should work. The code you posted is fine. How are you dumping it? You're using
pickle.dump
, notpickle.dumps
for a string? Your problem is almost certainly in the dumping code.