简体   繁体   English

如何在 python 3 中读取在 python 2.7 或 3 中复制的泡菜?

[英]How to read pickle that was dupmed in either python 2.7 or 3, in python 3?

  • I have read that I can read pickles that were dumped in python 2.7 in python 3 using我读过我可以读取在 python 3 中的 python 2.7 中使用的泡菜

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

  • Obviously, I can read pickles that were dumped in python 3 using显然,我可以使用以下命令读取在 python 3 中转储的泡菜

    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?如何测试我正在尝试读取哪种类型的泡菜以使用正确的方法?

inspired by @DeepSpace:灵感来自@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

使用 if else: 尝试在没有编码的情况下进行正常加载并进行一些读取,如果成功则使用 encoding='latin1' 进行 else 加载

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM