2013-04-28 41 views
0

我正在製作一個生物模擬器,在每個生物的最後,應該將其信息的json形式轉儲到單個文件中。然後在早上,模擬器應該能夠從該單個文件中提取所有生物信息,並像以前那樣重新實現它們。 那麼,有沒有辦法有:python,加載多個東西的實例

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) 

的問題是,在第二部分,我不知道如何單獨讀取每個生物。我怎樣才能做到這一點?

+5

'pickle'的類實例。 – Blender 2013-04-28 21:37:16

+0

什麼是泡菜? – EasilyBaffled 2013-04-28 21:59:54

+0

http://docs.python.org/2/library/pickle.html – Blender 2013-04-28 22:02:58

回答

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)