簡體   English   中英

如何以 json 格式存儲來自用戶的輸入值?

[英]How to store input values from user in json format?

我使用下面的代碼來存儲學生信息,但我只得到一個值出現在 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)

為了

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

您需要將“w”更改為“a”

到 append 文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM