TypeError:描述符“write”需要'_拜特西奥'对象,但收到'str'

2024-06-16 12:02:39 发布

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

我使用Python pickling来序列化数据并写入流。 (然后从流中读取 代码如下:

import pickle
import io
import pprint

class SimpleObject:

    def __init__(self, name):
        self.name = name
        self.name_backwards = name[::-1]


data = []
data.append(SimpleObject('pickle'))
data.append(SimpleObject('preserve'))
data.append(SimpleObject('last'))

print (type(data))

# simulate a file
out_s = io.BytesIO

print (type(out_s))

for o in data:
    print('WRITING : {} ({})'.format(o.name, o.name_backwards))
    # writing to the stream
    print (type(o))
    pickle.dump(o, out_s)
    out_s.flush() 

写入流时出错-

^{pr2}$

当我打印类型(o)时,它将其打印为(SimpleObject的)实例

WRITING : pickle (elkcip)
<type 'instance'>

那么,为什么会出现此错误?如何修复?在


Tags: nameioimportselfdata序列化typeout