Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中将一个json文件作为输出?_Python_Json - Fatal编程技术网

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

如何在python中将一个json文件作为输出?,python,json,Python,Json,我目前在python代码中保存一个组合的json文件时遇到问题,但它的作用是将最新的“结果”保存在json文件中,而不是所有结果,因此我必须将所有不同的结果保存在单独的json文件中,但我想将其存储在单个feculty.json文件中,我该如何做 这是我的密码: outputPath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'output') if os.path.isdir(outputPath) is Fa

我目前在python代码中保存一个组合的json文件时遇到问题,但它的作用是将最新的“结果”保存在json文件中,而不是所有结果,因此我必须将所有不同的结果保存在单独的json文件中,但我想将其存储在单个feculty.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
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"
    }
]

是否要删除并向其写入更多数据?但是你最终不会得到一个有效的JSON文件。最新的而不是所有的是什么意思?您的代码段是否在实际代码中的for循环中?您的代码段有点混乱。从
return
语句中,我猜这是在循环中调用的函数的一部分。以后,请尝试发布一个。MCVE使人们更容易准确地理解您的问题所在,也使他们更容易编写有用的答案,因为他们可以简单地编辑和测试您提供的代码。