0

我正在制作一个生物模拟器,在每个生物的末尾,应该将其信息的 json 形式转储到一个文件中。然后在早上,模拟器应该能够从单个文件中提取所有生物信息,并像以前一样重新实例化它们。那么有没有办法:

newDailyFile = path+day
with open(newDailyFile, "a") as file:
    for i in creatures:
        dump({'name':name, 'numbers':n, 'strings':s, 'x':x, 'y':y}, file, indent=4)
        #The only thing that is guaranteed to be unique is the name

然后

with open("text") as file:
    result = load(file)
    for something in result:
        creature = Creature(result)

问题在第二部分,我不知道如何单独阅读每个生物。我怎样才能做到这一点?

4

1 回答 1

0

我只需要改变我写字符串和读回它们的方式。

newDailyFile = path+day
with open(newDailyFile, "a") as file:
    for i in creatures:
        dump({'name':name, 'numbers':n, 'strings':s, 'x':x, 'y':y}, file) #removed indent so each one is online
        file.write("\n")#or else they will all be on the same line

然后

with open(newDailyFile) as file:
    lines = file.readlines() #Gets each one line by line, then I can load them
    for i in lines:
        result = loads(i)
于 2013-04-28T22:08:02.617 回答