我目前在 python 代码中保存一个组合的 json 文件时遇到问题,但它的作用是将最新的“结果”保存在 json 文件中,而不是全部,所以我必须将所有不同的结果保存在单独的 json 文件中但我想将其存储在单个 coach.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
最佳答案
您可以将所有dict
收集到一个列表中,然后将该列表保存为 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"
}
]
关于python - 如何在Python中将一个json文件作为输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31893638/