是什么导致错误"_pickle.UnpicklingError:无效的加载键'". [英] What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

查看:5099
本文介绍了是什么导致错误"_pickle.UnpicklingError:无效的加载键'".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在一个阵列上存储5000个数据元素.这5000个元素存储在一个现有文件中(因此它不为空).

I'm trying to storage 5000 data elements on an array. This 5000 elements are storage on an existent file (therefore it's not empty).

但是我遇到错误,我不知道是什么原因造成的.

But I'm getting an error and I don't know what is causing it.

IN:

def array():

    name = 'puntos.df4'

    m = open(name, 'rb')
    v = []*5000

    m.seek(-5000, io.SEEK_END)
    fp = m.tell()
    sz = os.path.getsize(name)

    while fp < sz:
        pt = pickle.load(m)
        v.append(pt)

    m.close()
    return v

OUT:

line 23, in array
pt = pickle.load(m)
_pickle.UnpicklingError: invalid load key, ''.

推荐答案

酸洗是递归的,而不是顺序的.因此,要腌制一个列表,pickle将开始腌制该包含的列表,然后腌制第一个元素……潜入第一个元素并腌制相关性和子元素,直到第一个元素被序列化.然后移动到列表的下一个元素,依此类推,直到最终完成列表并完成对包含列表的序列化.简而言之,除了某些特殊情况外,很难将递归泡菜视为顺序的.如果要以特殊方式load,最好在dump上使用更智能的模式.

pickling is recursive, not sequential. Thus, to pickle a list, pickle will start to pickle the containing list, then pickle the first element… diving into the first element and pickling dependencies and sub-elements until the first element is serialized. Then moves on to the next element of the list, and so on, until it finally finishes the list and finishes serializing the enclosing list. In short, it's hard to treat a recursive pickle as sequential, except for some special cases. It's better to use a smarter pattern on your dump, if you want to load in a special way.

最常见的腌菜,它是用单个dump腌制所有内容到文件中的-但随后,您必须使用单个load一次将所有内容腌制成load.但是,如果您打开文件句柄并执行多个dump调用(例如,对列表中的每个元素调用一次,或选定元素的元组),则您的load将镜像...您打开文件句柄并执行多个load调用直到拥有所有列表元素并可以重建列表.但是,选择性地仅load仅某些列表元素仍然不容易.为此,您可能必须使用klepto之类的包将列表元素存储为dict(以元素或块的索引为键),这样可以将腌制的dict分解为透明地存储多个文件,并可以轻松加载特定元素.

The most common pickle, it to pickle everything with a single dump to a file -- but then you have to load everything at once with a single load. However, if you open a file handle and do multiple dump calls (e.g. one for each element of the list, or a tuple of selected elements), then your load will mirror that… you open the file handle and do multiple load calls until you have all the list elements and can reconstruct the list. It's still not easy to selectively load only certain list elements, however. To do that, you'd probably have to store your list elements as a dict (with the index of the element or chunk as the key) using a package like klepto, which can break up a pickled dict into several files transparently, and enables easy loading of specific elements.

在泡菜文件中保存和加载多个对象?

这篇关于是什么导致错误"_pickle.UnpicklingError:无效的加载键'".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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