解开文件时出现值错误 [英] Value Error when unpickling a file

查看:69
本文介绍了解开文件时出现值错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了一个包含两个腌制对象的文件-它以.pk文件的形式发送给我.有人告诉我它有两个对象,但是,我尝试删除这些文件的尝试失败.

I have been given a file that contains two pickled objects- it was sent to me as a .pk file. I was told it had two objects, however, my attempt to unpikle these files is unsuccessful.

第一个腌制对象包含一个带有罗马数字的数字对字典,第二个腌制对象包含一个带有罗马数字的字典对.我该如何分别解开这两个词典?

The first pickled object contains a dictionary of pairs of numbers with their roman numerals, and the second contains dictionary pairs of roman numerals with their numbers. How can I unpickle these two dictionaries separately?

这是我下面的内容以及收到的错误消息:

This is what I have below, along with the error message I am receiving:

import pickle
x,y=pickle.load(open("C://Users//Documents//roman.pk", "rb"))
print(x,y)

错误消息:

ValueError: too many values to unpack (expected 2)

推荐答案

pickle.load将仅加载在文件中找到的第一个腌制对象.在您的情况下,该词典具有两个以上的键,因此x, y = pickle.load(...)失败,因为它试图将词典的键拆包为标识符xy.

pickle.load will only load the first pickled object that it finds in the file. In your case, that's a dictionary with more than two keys, so x, y = pickle.load(...) fails because it's trying to unpack the dictionary's keys to the identifiers x and y.

相反,您应该open文件一次,并load从文件两次:

Instead, you should open the file once, and load from it twice:

with open("...roman.pk") as file_:
    first_dict = pickle.load(file_)  # file pointer is now at end of first object
    second_dict = pickle.load(file_)  # read in second object

或者,鼓励任何向您提供文件的人将这两个字典放在一个对象中,例如元组(first_dict, second_dict)pickle单个对象;这比依赖于准确知道文件中有多少个腌制对象要容易得多.

Alternatively, encourage whoever is supplying you with the file to put the two dictionaries into a single object, e.g. a tuple (first_dict, second_dict) and pickle that single object; this is much easier than relying on knowing exactly how many pickled objects are in the file.

这篇关于解开文件时出现值错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆