如何在给定条件下将json字典转储到多个文件中

2024-06-17 10:28:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从用户输入中为每个学生创建一个单独的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)

Tags: 文件to用户namejsoninputget字典
2条回答

代码的问题是每次变量名的值都会被输入的姓氏覆盖。尝试为每次输入迭代保存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 = {}

name=''
d=''
while True:
    exit = input('Do you want to add another input (y/n)?')
    print(exit)
    if exit.lower()=='n':
        break
    else:
        name, d = get_input()
        out[name] = d
        with open(name + '.json','a') as j:
            json.dump(out, j, indent= 2)
        out={}
#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)

else:
    if 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)
    enter code here

如果我正确地理解了您的问题,您需要为每个人创建一个新的json文件,并且每个人都有自己对应的字典。在

一个解决办法是创建一个字典词典。在

out = {
    'jessica':{'date': x, 'hours': y},
    'wendy':{'date': x2, 'hours': y2}
}

然后循环查看out字典。在

^{pr2}$

相关问题 更多 >