我试图从用户输入中为每个学生创建一个单独的json文件。在
目前,我只能将所有信息转储到一个文件中,但我需要根据用户输入的名称将字典放在单独的文件中。在
我还试图在每次用户输入时更新一个字典
import json
def get_input():
#user input to record in log
name = input("Name:")
d = {} #my dictionary
d['date'] = input('Enter a date in YYYY-MM-DD format:')
d['hours'] = input("Hours:")
return(name,d)
out = {}
while True:
exit = input('Do you want to add another input (y/n)?')
if exit.lower() == 'n':
break
else:
name, d = get_input()
out[name] = d
#dump into separate file according to name from user input
if name == 'Jessica':
with open('jessica.json','a') as j:
json.dump(out, j, indent= 2)
elif: name == 'Wendy':
with open('wendy.json','a') as w:
json.dump(out, w, indent= 2)
else:
with open('tat.json','a') as t:
json.dump(out, t, indent= 2)
代码的问题是每次变量名的值都会被输入的姓氏覆盖。尝试为每次输入迭代保存json文件。但是改变字典的名字,因为在每次迭代中内容都是累积的。在
如果我正确地理解了您的问题,您需要为每个人创建一个新的json文件,并且每个人都有自己对应的字典。在
一个解决办法是创建一个字典词典。在
然后循环查看out字典。在
^{pr2}$相关问题 更多 >
编程相关推荐