如何在python 3中读取在python 2.7或3中被腌制的泡菜? [英] How to read pickle that was dupmed in either python 2.7 or 3, in python 3?

查看:118
本文介绍了如何在python 3中读取在python 2.7或3中被腌制的泡菜?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 我已阅读到可以读取在python 3中使用python 2.7转储的酱菜

  • I have read that I can read pickles that were dumped in python 2.7 in python 3 using

content = pickle.load(o, encoding='latin1')

很明显,我可以使用

content = pickle.load(o)

我的问题是,我不知道我的酱菜的来源.可能是一个.

My problem is, I can't know the source of my pickle. It could be either one.

如何使用正确的方法测试要尝试读取的泡菜类型?

How can I test which type of pickle I am trying to read in order to use the correct method?

推荐答案

受@DeepSpace启发:

inspired by @DeepSpace:

def load(path):
    print(f"loading pkl: {os.path.abspath(path)}")
    assert os.path.isfile(path)
    try:
        with open(path, "rb") as f:
            content = pickle.load(f)
    except UnicodeDecodeError:  # pickle was created with python 2.7
        with open(path, "rb") as f:
            content = pickle.load(f, encoding='latin1')

    return content

这篇关于如何在python 3中读取在python 2.7或3中被腌制的泡菜?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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