问题
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