我想根据用户的输入使用 JSON 创建数据库。我已经编写了这段代码,但它用新数据替换了整个文件,并且不更新现有的 JSON 文件。文件database.json给出的输出为{"Employee ID": "ID2", "Employee Name": "Friendrich", "Domain": "Engineering", "Employee Type": "Permanent", "Start Date": "01.02.2020", "End Date": "28.02.2021"}import jsons_id = input('employeeID')s_name = input('employeeName')s_domain = input('domain')s_type = input('employeeType')s_from = input('start-date')s_until = input('end-date')database = { 'Employee ID' : s_id, 'Employee Name' : s_name, 'Domain' : s_domain, 'Employee Type' : s_type, 'Start Date' : s_from, 'End Date' : s_until }with open('database.json') as json_file: data = json.load(json_file)data.update(database)with open('database.json', 'w') as json_file: json.dump(database, json_file)使用新输入时,json 文件应将数据添加到现有文件中。所以输出应该是{"Employee ID": "new ID", "Employee Name": "input name", "Domain": "input domain", "Employee Type": "input type", "Start Date": "input date", "End Date": "input date"}, {"Employee ID": "ID2", "Employee Name": "Friendrich", "Domain": "Engineering", "Employee Type": "Permanent", "Start Date": "01.02.2020", "End Date": "28.02.2021"}, 我创建这个数据库是为了找到具有特定过滤器的所有员工。假设所有具有工程领域的员工。使用 JSON 作为数据库是一个好习惯吗?
2 回答
![?](http://img1.sycdn.imooc.com/54584c5e0001491102200220-100-100.jpg)
芜湖不芜
TA贡献1796条经验 获得超7个赞
每次保存数据时都会截断文件。
使用“ a ”而不是“ w ”作为打开模式。
代替
with open('database.json', 'w') as json_file: json.dump(database, json_file)
和
with open('database.json', 'a') as json_file: json.dump(database, json_file)
添加回答
举报
0/150
提交
取消