无法加载腌制的对象 [英] Cannot load pickled object

查看:82
本文介绍了无法加载腌制的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题是当我尝试加载 pickled 对象.我尝试同时使用pickle.loadspickle.load这是结果:

The problem I am having is when I try to load the pickled object. I have tried using both pickle.loads and pickle.load Here are the results:

pickle.loads:

TypeError:'str'不支持缓冲区接口

TypeError: 'str' does not support the buffer interface

pickle.load:

TypeError:文件必须具有"read"和"readline"属性

TypeError: file must have 'read' and 'readline' attributes

有人可以告诉我我在此过程中做错了什么吗?

Can someone please tell me what I am doing wrong in this process?

elif str(parser) == "SwissWithdrawn_Parser":
    # swissprot name changes
    print("Gathering SwissProt update info...")
    cache_hits = 0
    cache_misses = 0
    files = set()

    for f in os.listdir("out/cache/"):
        if os.path.isfile("out/cache/" + f):
            files.add(f)

    for name in sp_lost_names:

        cached = False
        url = (
            "http://www.uniprot.org/uniprot/?query=mnemonic%3a"
            + name
            + "+active%3ayes&format=tab&columns=entry%20name"
        )
        hashed_url = str(hash(url))

        ################### For Testing Only - use cache ##################
        if hashed_url in files:
            cached = True
            cache_hits += 1
            content = pickle.loads("out/cache/" + hashed_url)  # <-- problematic line
        else:
            cache_misses += 1
            content = urllib.request.urlopen(url)

        # get the contents returned from the HTTPResponse object
        content_list = [x.decode().strip() for x in content.readlines()]
        if not cached:
            with open("out/cache/" + hashed_url, "wb") as fp:
                pickle.dump(content_list, fp)
        ####################################################################

        # no replacement
        if len(content_list) is 0:
            change_log["swiss-names"] = {name: "withdrawn"}
        # get the new name
        else:
            new_name = content_list[1]
            change_log["swiss-names"] = {name: new_name}

推荐答案

您需要先读取文件(作为二进制文件bytes)并使用pickle.loads(),或传递打开的文件pickle.load()命令的对象.后者是可取的:

You need to either read the file first (as binary bytes) and use pickle.loads(), or pass an open file object to the pickle.load() command. The latter is preferable:

with open('out/cache/' +hashed_url, 'rb') as pickle_file:
    content = pickle.load(pickle_file)

这两种方法都不支持从文件名中加载泡菜.

Neither method supports loading a pickle from a filename.

这篇关于无法加载腌制的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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