我正在制作一个生物模拟器,在每个生物的末尾,应该将其信息的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)
问题出在第二部分,我不知道如何单独阅读每个生物。我怎么能这样做?
答案 0 :(得分: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)