【发布时间】:2021-12-29 02:55:51
【问题描述】:
这是我的 config.json
{
"dictionary": [
{
"name": "A",
"rollno": "B",
"cgpa": "C",
"phonenumber": "D"
},
{
"name": "E",
"rollno": "F",
"cgpa": "G",
"phonenumber": "H"
}
]}
这是我的代码
import os
import json
name = input("Name : ")
rollno = input("No : ")
cgpa = input("cgpa : ")
phonenumber = input("Phone No. : ")
dictionary ={
"name" : f"{name}",
"rollno" : f"{rollno}",
"cgpa" : f"{cgpa}",
"phonenumber" : f"{phonenumber}"
}
def write_json(data, filename="Discord\Test Field\config.json"):
with open(filename,'r+') as file:
file_data = json.load(file)
file_data["dictionary"].append(data)
file.seek(0)
json.dump(file_data, file, indent = 4)
with open("Discord\Test Field\config.json", 'r') as f:
json_load = json.load(f)
name_in_dict = name in json_load
if name_in_dict == True:
print("Key already exist")
else:
write_json(dictionary)
我想检查 name = "A" 是否已经存在,如果已经存在则取消输入,如果不存在 write_json 将运行它 func
【问题讨论】: