2015-08-08 68 views
2

我目前有問題在我的Python代碼中保存一個組合的json文件,但它做了什麼呢一個保存在json文件中的最新「結果」,並不是所有的,所以我不得不保存所有不同的結果在單獨的json文件中但相反,我想將它存儲在單個faculty.json文件中,我該怎麼做?如何在python中將一個json文件作爲輸出?

這裏是我的代碼:

outputPath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'output') 
    if os.path.isdir(outputPath) is False: 
     os.makedirs(outputPath) 
    result = {'empid': facultyID, 'name': name, 'school': school, 'designation': designation, 'room': room, 'intercom': intercom, 'email': email, 'division': division, 'open_hours': openHours} 
    with open('output/faculty.json', 'w') as outfile: 
     json.dump(result, outfile) 
    return result 
+3

你想[打開''a''ppend模式文件(https://docs.python.org/2/tutorial/inputoutput。 HTML#讀寫文件),並寫入更多的數據呢?但是,你最終不會得到一個有效的JSON文件。 –

+0

你是什麼意思最新的,而不是全部?您的代碼片段是否在實際代碼中的for循環中? –

+0

你的代碼片段有點混亂。從'return'語句我_guess_它是你在一個循環中調用的函數的一部分。 –

回答

2

您可以收集所有dict S的到一個列表,然後將該列表保存爲JSON文件。這是一個簡單的演示過程。該程序重新加載JSON文件以驗證它是合法的JSON,並且它包含我們所期望的。

import json 

#Build a simple list of dicts 
s = 'abcdefg' 
data = [] 
for i, c in enumerate(s, 1): 
    d = dict(name=c, number=i) 
    data.append(d) 

fname = 'data.json' 

#Save data 
with open(fname, 'w') as f: 
    json.dump(data, f, indent=4) 

#Reload data 
with open(fname, 'r') as f: 
    newdata = json.load(f) 

#Show all the data we just read in 
print(json.dumps(newdata, indent=4)) 

輸出

[ 
    { 
     "number": 1, 
     "name": "a" 
    }, 
    { 
     "number": 2, 
     "name": "b" 
    }, 
    { 
     "number": 3, 
     "name": "c" 
    }, 
    { 
     "number": 4, 
     "name": "d" 
    }, 
    { 
     "number": 5, 
     "name": "e" 
    }, 
    { 
     "number": 6, 
     "name": "f" 
    }, 
    { 
     "number": 7, 
     "name": "g" 
    } 
] 
相關問題