如何读取 python 2.7 或 python 3 中被复制的 pickle?

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


我的问题是,我不知道泡菜的来源。两者都可以。

如何测试我正在尝试阅读哪种泡菜以便使用正确的方法?

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

受@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