Python 无法加载腌制对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18261898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:18:52  来源:igfitidea点击:

Cannot load pickled object

pythonpython-3.xpickle

提问by Houdini

The problem I am having is when I try to load the pickledobject. I have tried using both pickle.loadsand pickle.loadHere are the results:

我遇到的问题是当我尝试加载腌制对象时。我尝试使用两者pickle.loadspickle.load结果如下:

pickle.loads:

pickle.loads

TypeError: 'str' does not support the buffer interface

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

pickle.load:

pickle.load

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

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

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}

采纳答案by Martijn Pieters

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

您需要先读取文件(作为 binary bytes)并使用pickle.loads(),或者将打开的文件对象传递给pickle.load()命令。后者更可取:

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

Neither method supports loading a pickle from a filename.

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