Python 如何以json格式存储来自用户的输入值?

Python 如何以json格式存储来自用户的输入值?,python,json,Python,Json,我使用下面的代码来存储学生信息,但json文件中只显示一个值 import json def get_studentdetails(): data={} data['name']=input("Enter Student name") data['class']=input("Enter Class") data['maths']=input("Enter Marks for Maths") d

我使用下面的代码来存储学生信息,但json文件中只显示一个值

import json

def get_studentdetails():
    data={}
    data['name']=input("Enter Student name")
    data['class']=input("Enter Class")
    data['maths']=input("Enter Marks for Maths")
    data['eng']=input("Enter English Marks")
    data['sci']=input("Enter Science Marks")
    return (data)

out={}
while True:
    quit=input("Enter Y/N to continue")
    if quit.lower()=='n':
        break
    else:
       out['Student_Detail']= get_studentdetails()

    with open('students.json','w') as file:
        json.dump(out,file,indent=2)

这是因为您在每次while循环后都会覆盖您的文件。在外部写入文件。另外,您希望将学生存储到列表中

import json

def get_studentdetails():
    data={}
    data['name']=input("Enter Student name")
    data['class']=input("Enter Class")
    data['maths']=input("Enter Marks for Maths")
    data['eng']=input("Enter English Marks")
    data['sci']=input("Enter Science Marks")
    return (data)
out=[]
while True:
    quit=input("Enter Y/N to continue")
    if quit.lower() == 'n':
        break
    record = get_studentdetails()
    out.append(record)


with open('students.json','w') as file:
    json.dump(out,file,indent=2)


这是因为您在每次while循环后都会覆盖您的文件。在外部写入文件。另外,您希望将学生存储到列表中

import json

def get_studentdetails():
    data={}
    data['name']=input("Enter Student name")
    data['class']=input("Enter Class")
    data['maths']=input("Enter Marks for Maths")
    data['eng']=input("Enter English Marks")
    data['sci']=input("Enter Science Marks")
    return (data)
out=[]
while True:
    quit=input("Enter Y/N to continue")
    if quit.lower() == 'n':
        break
    record = get_studentdetails()
    out.append(record)


with open('students.json','w') as file:
    json.dump(out,file,indent=2)

为了

您需要将“w”改为“a”

要附加文件,请执行以下操作

您需要将“w”改为“a”

附加文件