如何在 python 中使用 pickle 保存带有列表的对象?

How can i save object with list using pickle in python?

我正在尝试用另一个 class 对象的列表保存对象。

    def loadBot(self, name):

       BotFile = open('../Bots/' + name, 'rb+')

       self.CurrentBot = pickle.load(BotFile)

       BotFile.close() # Closes file

    def saveBot(self, bot):

       BotFile = open('../Bots/' + bot.Name, 'wb+') 

       BotFile.truncate() # Clear File
       pickle.dump(bot, BotFile, protocol=pickle.HIGHEST_PROTOCOL) 

       BotFile.close() # Close file

这些是我用来加载对象和保存的函数。在对象 Bot 中,我有对象列表 'Blueprint' 和函数添加蓝图。

    class ChatBot:

       Name = 'DefaultName'
       Token = 'DefaultToken'
       bot_blueprints = []

       def __init__(self, Name, Token):
         self.Name = Name
         self.Token = Token

      def addBlueprint(self):
        self.bot_blueprints.append(Blueprint(len(self.bot_blueprints))) 

我正在添加新元素并在保存之前和之后检查列表大小

app.loadBot('A')
print(len(app.CurrentBot.bot_blueprints))
app.CurrentBot.addBlueprint()
app.saveBot(app.CurrentBot)
print(len(app.CurrentBot.bot_blueprints))

它从 0 开始,添加 bp 后变为 1。在此之后我关闭应用程序,第二次启动它,我的代码应该在打开后写入 1,在添加后写入 2,但它仍然是 0 和 1。文件大小在增加但是pickle 无法正确加载我的文件。

您编写代码的方式 bot_blueprints 是 class 级变量,而不是实例级变量。因此整个程序只有一个,而不是每个 ChatBot

我将 class 重新排列为:

class ChatBot:
   def __init__(self, name, token):
     self.name = name
     self.token = token
     self.bot_blueprints = []

  def addBlueprint(self):
    self.bot_blueprints.append(Blueprint(len(self.bot_blueprints)))