无法加载pickle对象。

126

我的问题是当我尝试加载pickled对象时。我已经尝试过使用pickle.loadspickle.load两种方法。以下是结果:

pickle.loads:

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

pickle.load:

类型错误:文件必须具有“read”和“readline”属性

请问有人能告诉我在这个过程中我错在哪里了吗?

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}
2个回答

173

你需要先以二进制bytes的形式读取文件,然后使用pickle.loads()方法,或将一个打开的文件对象传递给pickle.load()命令。后者更可取:

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

两种方法都不支持从文件名加载pickle。


8

如果你正在将 Python2 转换为 Python3,并且遇到了以下错误,那么请注意:Python2 和 Python3 处理字节的方式不同,因此需要在打开文件时使用 'b' 选项。例如,在 Python2 中使用 open(file, 'r') as f: my_list = pickle.load(f) 是可行的,但在 Python3 中则不行。相反,你必须使用 open(file, 'rb') as f: my_list = pickle.load(f)


我遇到了 _pickle.UnpicklingError 错误:遭遇了一个 load persistent id 指令,但未指定 persistent_load 函数。同时 pickle 文件已经存在,如 data.pickle。 - user5520049

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接