如何在python中将一个json文件作为输出?

问题描述:

我目前有问题在我的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_它是你在一个循环中调用的函数的一部分。 –

您可以收集所有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" 
    } 
]