制作一个Python简易登录系统
代码:
import os.path
import json
import hashlib
UI = """
用户登录系统
1.注册
2.登录
"""
def load(path):
return json.load(open(path, "rt"))
def save(dic, path: str):
json.dump(dic, open(path, "wt"))
while True:
print(UI)
num = input("请输入你的选择:")
if num == "1":
if os.path.exists("users.bin"):
dc = load("users.bin")
else:
dc = {}
account = input("请输入账户:")
password = input("请输入密码:")
confirm = input("请确认密码:")
if dc.get(account):
print("账户已存在请重新输入")
elif password == confirm:
md5 = hashlib.md5(password.encode())
encrypt = md5.hexdigest()
dc[account] = encrypt
save(dc, "users.bin")
print("注册成功")
elif num == "2":
# 输入账户密码
account = input("请输入账户:")
password = input("请输入密码:")
md5 = hashlib.md5(password.encode())
# 读取users.bin·得到一个字典
dc = load("users.bin")
# dc.get判断用户的账户是否存在
if dc.get(account):
# dc[account]==输入的密码
if dc[account] == md5.hexdigest():
print("登录成功")
else:
print("密码错误")
else:
print("不存在用户")
else:
pass
# 登录成功 否则登录失败
结果:
![](https://img-blog.csdnimg.cn/direct/56390d849b9c4ceaa1004236cea3797c.png)
![](https://img-blog.csdnimg.cn/direct/696cb4d6571a4a068fd89d31bc54392f.png)
![](https://img-blog.csdnimg.cn/direct/55337df6b59f42f99ec8924f1cc86957.png)