使用pickle或dill保存类数据无法正常工作。

18 浏览
0 Comments

使用pickle或dill保存类数据无法正常工作。

我想将投票类数据的状态保存到文件中,如果我的脚本重新启动,则加载回来。我弹出我的程序的一部分来复制问题。以下是我的文件。

pickleclass.py

#POLL RECORD
class POLL:
  title = ''
  votes = {}
  duration = 0
  secenekler = 0
  sure = ""
  polltype = -1 # -1 initial, 0 = %, 1 = Sayi
  chat_id = None
  message_id = None
  def reset():
    POLL.title = ''
    POLL.votes.clear()
    POLL.duration = 0
    POLL.secenekler = 0
    POLL.sure = ""
    POLL.polltype = -1
    POLL.chat_id = None
    POLL.message_id = None

fxns.py

def save_to_file(obj, filename):
    """
    Saves obj to file named with fn as pickly object.
    """
    import pickle
    with open(filename, 'wb') as output:  # Overwrites any existing file.
        pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)
def load_from_file(fn):
    import pickle
    """
    reads from file given in fn and returns object of dump pickle file
    """
    return pickle.load( open( fn, "rb" ) )

save.py

import pickleclass as pk
import fxns as fxn
Poll_file = "p.dump"
poll = pk.POLL
poll.title = "TEST TITLE"
poll.votes['VOTE 1'] = 1
poll.votes['VOTE 2'] = 2
poll.votes['VOTE 3'] = 3
poll.duration = 0.4
poll.secenekler = 1
poll.sure = "23:55"
poll.polltype = 1
poll.chat_id = 112431
poll.message_id = 324
print("-"*55)
print("-"*55)
bozo = vars(poll)
for key in bozo.keys():
    print(key, "=", bozo[key])
print("-"*55)
fxn.save_to_file(poll, Poll_file)

首先我调用save.py创建类并保存它。保存成功结束。然后我调用下面的load.py来加载保存的内容。但是它加载的是空的类数据,就像是新创建的一样。

输出save.py文件如下:

('reset', '=', )
('__module__', '=', 'pickleclass')
('sure', '=', '23:55')
('secenekler', '=', 1)
('title', '=', 'TEST TITLE')
('__doc__', '=', None)
('votes', '=', {'VOTE 2': 2, 'VOTE 3': 3, 'VOTE 1': 1})
('polltype', '=', 1)
('chat_id', '=', 112431)
('duration', '=', 0.4)
('message_id', '=', 324)

load.py

import pickleclass as pk
import fxns as fxn
Poll_file = "p.dump"
zozo = fxn.load_from_file(Poll_file)
zozo = vars(zozo)
for key in zozo.keys():
    print(key, "=", zozo[key])
print("-"*55)
print("-"*55)

当我加载文件并显示输出时,它是空的,如下所示。

('reset', '=', )
('__module__', '=', 'pickleclass')
('sure', '=', '')
('secenekler', '=', 0)
('title', '=', '')
('__doc__', '=', None)
('votes', '=', {})
('polltype', '=', -1)
('chat_id', '=', None)
('duration', '=', 0)
('message_id', '=', None)

我找不到问题所在。它加载类但不加载数据。

admin 更改状态以发布 2023年5月24日
0
0 Comments

装载过程正确执行:问题出在您的类没有正确实现。

请查看一些有关类和实例的材料(或一些SO上的帖子),特别是__init__函数、self 和类成员和实例成员等概念(在那篇文章中也有一个相关问题)。

然后看看pickle如何处理类,您就可以开始操作了。

编辑,显然,使用dill实现这个应该是可能的,可以查看这个SO帖子

0