尝试将类(在列表中)保存到文件

时间:2019-04-09 03:53:34

标签: python python-3.x class arraylist save

我正在尝试创建一个程序,可以在具有某些属性的游戏中存储NPC。例如:派系,个性,兴趣/爱好。为此,我创建了一个NPC类。

class NPC: #name, faction, position/job, character, interests, other
    def __init__ (self, name, faction, pos, char, inter, misc):
        self.name = name
        self.faction = faction
        self.pos = pos
        self.char = char
        self.inter = inter
        self.misc = misc

我为此程序创建了各种功能,例如创建新功能,更改NPC上的某些属性,删除它们,打印它们并对其进行排序。要存储NPC,我将它们附加到名为“ NPClist”的列表中。我想知道如何将此列表保存到.text文件或其他内容。到目前为止,我已经尝试了pickle模块,但这似乎不起作用。 (来源:How to save a list to a file and read it as a list type?

with open("NPCs.text", "wb") as file:
    pickle.dump(NPClist, file)

with open("NPCs.text", "rb") as file:
    NPClist.append(pickle.load(file))

我已将底部的一个放在程序的顶部,以便在启动程序时将其加载,而顶部的则放在循环的顶部,以便将其频繁保存。当我尝试启动程序时,收到错误消息。

AttributeError: Can't get attribute 'NPC' on <module '__main__' (built-in)>

还有其他方法可以解决此问题吗?还是我只是以错误的方式来腌制?

3 个答案:

答案 0 :(得分:2)

如果您只需要属性,我建议您仅保存属性,而不要尝试保存整个对象,并使用NPC中的一些辅助方法使此过程更容易。

例如:

class NPC:

    def dump(self):
        return [self.name, self.faction, self.pos, self.char, self.inter, self.misc]

    @staticmethod
    def build_npc(attributes):
        return NPC(*attributes)

然后您可以像这样处理转储:

NPClist = [NPC(...), NPC(...) ... ]

with open("NPCs.text", "wb") as file:
    pickle.dump([i.dump() for i in NPClist], file)

并像这样加载:

with open("NPCs.text", "rb") as file:
    NPClist = [NPC.build_npc(attributes) for attributes in pickle.load(file)]

答案 1 :(得分:1)

class NPC: #name, faction, position/job, character, interests, other
    def __init__ (self, name, faction, pos, char, inter, misc):
        self.name = name
        self.faction = faction
        self.pos = pos
        self.char = char
        self.inter = inter
        self.misc = misc

NPCList = []

handsome_npc = NPC(name='n1c9', faction='Good People', pos='Developer',
                   char='', inter='', misc='')

# create other NPCs as needed

NPCList.append(handsome_npc)

with open('NPCS.text', 'w') as f:
    f.write('name,faction,pos\n')
    # add other attrs as wanted
    for npc in NPCList:
        f.write(f"{npc.name}, {npc.faction}, {npc.pos}")
        # add other attrs as wanted
        f.write('\n')

试图写一些初学者可以使用的东西-因此可能有些冗长。马克·泰勒的答案也很好!

re:评论-您可以像下面这样访问文件:

class NPC: #name, faction, position/job, character, interests, other
    def __init__ (self, name, faction, pos, char, inter, misc):
        self.name = name
        self.faction = faction
        self.pos = pos
        self.char = char
        self.inter = inter
        self.misc = misc

npclist_built_from_file = []
with open('NPCS.text', 'r') as f:
    NPCS_lines = f.readlines()
    for line in NPCS_lines[1:]: # skip the header line
        npc = NPC(name=line[0], faction=line[1], pos=line[2], char='', inter='', misc='')
        # I used empty strings for char/inter/misc because they were empty in the original
        # example, but you would just fill out line[3], line[4], line[5] for the rest if wanted.
        npclist_built_from_file.append(npc)

然后,您可以对列表npclist_built_from_file中的NPC对象执行任何操作

答案 2 :(得分:0)

import ast

def stringifyNPC(c):
  return str(c.__dict__)

def unStringifyNPC(s):
  n = NPC(None,None,None,None,None,None)
  n.__dict__ = ast.literal_eval(s)
  return n