保存和加载对象并使用pickle - Saving and loading objects and using pickle

2021/12/02 06:29
阅读数 0

问题:

I´m trying to save and load objects using pickle module.我正在尝试使用pickle模块保存和加载对象。
First I declare my objects:首先我声明我的对象:

>>> class Fruits:pass
...
>>> banana = Fruits()

>>> banana.color = 'yellow'
>>> banana.value = 30

After that I open a file called 'Fruits.obj'(previously I created a new .txt file and I renamed 'Fruits.obj'):之后,我打开一个名为“Fruits.obj”的文件(之前我创建了一个新的 .txt 文件并将其重命名为“Fruits.obj”):

>>> import pickle
>>> filehandler = open(b"Fruits.obj","wb")
>>> pickle.dump(banana,filehandler)

After do this I close my session and I began a new one and I put the next (trying to access to the object that it supposed to be saved):完成此操作后,我关闭会话并开始一个新会话,然后放置下一个(尝试访问它应该保存的对象):

file = open("Fruits.obj",'r')
object_file = pickle.load(file)

But I have this message:但我有这样的消息:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python31\lib\pickle.py", line 1365, in load
encoding=encoding, errors=errors).load()
ValueError: read() from the underlying stream did notreturn bytes

I don´t know what to do because I don´t understand this message.我不知道该怎么做,因为我不明白这条消息。 Does anyone know How I can load my object 'banana'?有谁知道我如何加载我的对象“香蕉”? Thank you!谢谢!

EDIT: As some of you have sugested I put:编辑:正如你们中的一些人所建议的那样,我提出:

>>> import pickle
>>> file = open("Fruits.obj",'rb')

There were no problem, but the next I put was:没有问题,但我提出的下一个问题是:

>>> object_file = pickle.load(file)

And I have error:我有错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python31\lib\pickle.py", line 1365, in load
encoding=encoding, errors=errors).load()
EOFError

解决方案:

参考: https://stackoom.com/en/question/J0cN
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部