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

2024-09-29 21:49:20 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将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,并且在解码过程中不会撤消它。我怎样才能解开这个


Tags: 字符串selfnumberversionpickleutft1print
1条回答
网友
1楼 · 发布于 2024-09-29 21:49:20

我有一些代码在工作。代码:

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)

相关问题 更多 >

    热门问题