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

时间:2018-04-01 22:13:48

标签: python json dictionary logging user-input

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

2 个答案:

答案 0 :(得分:1)

您的代码的问题在于,每次使用输入的姓氏覆盖变量名称的值时。尝试为每次输入迭代保存json文件。但是更改字典的名称,因为在每次迭代中内容都已累积。

 new CopyWebpackPlugin([
      {from: './src/imgs', to: './imgs'}
    ]),
 new ImageminPlugin({
      { test: 'imgs/**'}
    }}),

答案 1 :(得分:0)

如果我理解你的问题,你想为每个人创建一个新的json文件,那个人有自己的相应字典。

一种解决方案是创建字典词典。

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

然后遍历 out 字典。

for name, dictionary in out.items():
    with open(name,'a') as j:
       json.dump(dictionary , j, indent= 2)