使用python将登录详细信息保存到json中



我使用python终端制作了一个登录表单。我从外部entries.json文件中获取了所有详细信息。效果很好!但我也想确保,如果用户没有登录,他们必须输入自己的姓名和密码,这样我就可以将其保存在文件中。但储蓄也存在问题。它无法保存到我想要的位置。请帮助我。
我的代码:-

import json
def write_json(new_data, filename='entries.json'):
with open(filename,'r+') as file:
file_data = json.load(file)
file_data.update(new_data)
file.seek(0)
json.dump(file_data, file, indent = 4)

f = open('entries.json', 'r+')
content = json.load(f)
out_file = open('entries2.json', 'w')
print('Welcome to our company!')
print('Pease enter your username here to login.')
name = input('Enter name: ')
for c in content:
for e in content['Entries']:
if name == e['User name']:
print('Please enter your password.')
password = input('Enter password: ')
if password == e['Password']:
print('Welcome,', name, 'you are now logged in!')
else:
print('Wrong password.')
break
else:
print('Your name is not in the file.')
print('You need to register.')
new_name = input('Please enter your name: ')
new_password = input('Please enter your password: ')
id = len(content['Entries'])

new_full = {"User name":f"{new_name}",
"Password": f"{new_password}",
"ID": f"{id + 1}"
}
write_json(new_full)
print(new_full)
print('Your name is added in the file.')

Json文件:-

{
"Entries": [
{
"User name": "Jerry",
"Password": "56_jerry_56",
"ID": 1
},
{
"User name": "Willy_Wonka",
"Password": "1111",
"ID": 2
},
{
"User name": "Anita",
"Password": "438200219",
"ID": 3
},
{
"User name": "John",
"Password": "john1",
"ID": 4
}
]
}

我的问题:-
我希望它在条目中添加new_full,但它在json文件中的条目之后添加它
确实是这样!

{
"Entries": [
{
"User name": "Jerry",
"Password": "56_jerry_56",
"ID": 1
},
{
"User name": "Willy_Wonka",
"Password": "1111",
"ID": 2
},
{
"User name": "Anita",
"Password": "438200219",
"ID": 3
},
{
"User name": "John",
"Password": "john1",
"ID": 4
}
],
"User name": "arya",
"Password": "arya1",
"ID": "5"
}

但我希望它是这样的!

{
"Entries": [
{
"User name": "Jerry",
"Password": "56_jerry_56",
"ID": 1
},
{
"User name": "Willy_Wonka",
"Password": "1111",
"ID": 2
},
{
"User name": "Anita",
"Password": "438200219",
"ID": 3
},
{
"User name": "John",
"Password": "john1",
"ID": 4
},
{
"User name": "arya",
"Password": "arya1",
"ID": 5
}
]
}

谢谢

在函数write_json:中尝试此代码

def write_json(new_data, filename='entries.json'):
with open(filename,'r+') as file:
file_data = json.load(file)
content['Entries'].append(new_data)
file_data.update(content)
file.seek(0)
json.dump(file_data, file, indent = 4)

最新更新