在 Python 中将使用 Pickle 序列化的对象转换为字符串

问题描述 投票:0回答:1

我正在尝试将

pickle.dumps
的输出转换为字符串,尽管我遇到了与字符串编码相关的错误消息。

错误代码:

import pickle

class TestClass:
    def __init__(self, number):
        self.number = number

t1 = TestClass(14)
s1 = pickle.dumps(t1)
str_version = s1.decode('utf-8', 'backslashreplace')
print(pickle.loads(str_version.encode('utf-8', 'backslashreplace')))

错误:

Traceback (most recent call last):
  File "C:\Users\ketha\Downloads\python_testing.py", line 11, in <module>
    print(pickle.loads(str_version.encode('utf-8', 'backslashreplace')))
_pickle.UnpicklingError: invalid load key, '\x5c'.

我认为这是因为当我将它转换为字符串时,它将

\x5c
(例如)转换为
\\x5c
并且在解码过程中不会撤消它。我怎么能撤消这个?

python character-encoding pickle
1个回答
2
投票

我有一些代码可以工作。代码:

import pickle
import sys

class TestClass:
    def __init__(self, number):
        self.number = number

t1 = TestClass(14)
s1 = pickle.dumps(t1)
str_version = s1.decode('unicode_escape')
decoded = pickle.loads(str_version.encode('utf-8', 'unicode_escape').replace(b'\xc2', b''))
print(decoded.number)
© www.soinside.com 2019 - 2024. All rights reserved.