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

纵然是瞬间 提交于 2020-01-24 12:52:27

问题


  • 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')

  • Obviously, I can read pickles that were dumped in python 3 using

    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?


回答1:


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



回答2:


use if else: try to do normal load without encoding and do some reads, if success proceed else load with encoding='latin1'



来源:https://stackoverflow.com/questions/59562586/how-to-read-pickle-that-was-dupmed-in-either-python-2-7-or-3-in-python-3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!