![](/img/trans.png)
[英]How to dynamically store values from .json file and compare them with user input in python?
[英]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.