python - 无法加载 pickle 对象

标签 python python-3.x pickle

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

pickle.loads:

TypeError: 'str' does not support the buffer interface

pickle.load:

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

谁能告诉我在这个过程中我做错了什么?

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() 命令的对象。后者更可取:

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

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

关于python - 无法加载 pickle 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18261898/

相关文章:

python - 处理多个应用程序覆盖 Django 中的管理命令

python - 关于python类方法的属性的问题

python - NameError: name '' is not defined, trying to make a to-do list CLI 应用程序

python - pickle.dump 遇到 RuntimeError : maximum recursion depth exceeded in cmp

python - 使用 Selenium 时 Cookie 不起作用

python - 在python上进行ARP请求

python - 在 Python 中将字符串转换为枚举

python - 有和没有显式基类的类之间 __dict__ 的差异

Python 异步/aiohttp : ValueError: too many file descriptors in select() on Windows

javascript - Django:如何在过滤后刷新表格而不刷新整个页面?