将用户输入存储到JSON文件python中



有没有办法将这些输入存储到字典JSON文件中,因此当我导入熊猫时,很容易分析?如果可以以一种更简单的方式编写此代码(例如Loop(

#student's profile to be saved in file separately
j = open("jessica.txt",'a')
w = open("wendy.txt", 'a')
t = open("tatiana.txt", 'a')
#user input to record the log
name = input("Name:")
date = input('Enter a date in YYYY-MM-DD format:')
hours = input("Hours:")
rate = input("Rate:")
topic = input('Topic:')
if name == 'Jessica':
    j.writelines("Date:" + date + 'n')
    j.writelines("Hours:" + hours + 'n')
    j.writelines("Rate:" + rate + 'n')
elif name == 'Tatiana':
    t.writelines("Date:" + date + 'n')
    t.writelines("Hours:" + hours + 'n')
    t.writelines("Rate:" + rate + 'n')
else:
    w.writelines("Date:" + date + 'n')
    w.writelines("Hours:" + hours + 'n')
    w.writelines("Rate:" + rate + 'n')

这是一个示例:

import json
def get_inputs():
    #user input to record the log
    name = input("Name:")
    d =  {}
    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_inputs()
        out[name] = d
with open('names.json','w') as f:
    json.dump(out, f, indent=2)

,然后:

import pandas as pd
print(pd.read_json('names.json'))

您有:

          Jessica
date   2014-12-01
hours          12

相关内容

  • 没有找到相关文章

最新更新