# 1:编写用户登录接口
# 2、输入账号密码完成验证,验证通过后输出"登录成功"
# 3、可以登录不同的用户.
# 4、同一账号输错三次锁定,(提示:锁定的用户存入文件中,这样才能保证程序关闭后,该用户仍然被锁定)
def Read_txt():
users_psw = {}
wrong = {}
with open('users_psw.txt', encoding='utf-8') as file1:
filecontents = file1.readlines()
for i in filecontents:
users = i.replace('\n', '').split(':')[0]
psw = i.replace('\n', '').split(':')[1]
users_psw[users] = psw
print(users_psw)
with open('wrong.txt', encoding='utf-8') as file2:
filecontents = file2.readlines()
for i in filecontents:
users = i.replace('\n', '').split(':')[0]
psw = i.replace('\n', '').split(':')[1]
wrong[users] = psw
print(wrong)
return users_psw, wrong
def To_txt(users_psw, wrong):
with open(f'users_psw.txt', encoding='utf-8', mode='w') as file:
for k, v in users_psw.items(): # 遍历字典中的键值
file.write(str(k) + ':') # 键和值分行放,键在单数行,值在双数行
file.write(str(v) + '\n')
with open(f'wrong.txt', encoding='utf-8', mode='w') as file:
for k, v in wrong.items(): # 遍历字典中的键值
file.write(str(k) + ':') # 键和值分行放,键在单数行,值在双数行
file.write(str(v) + '\n')
def Check_user_psw(user):
psw = input('请输入密码:')
if psw == users_psw[user]:
print('用户名和密码输入正确!')
else:
num = 2
while num > 0:
psw = input(f'用户名正确,密码错误!请重新输入,还有{num}次机会:')
if psw == users_psw[user]:
print('用户名和密码输入正确!')
break
else:
num -= 1
else:
print(f'{user}用户密码输入错误,达三次,已锁定!')
wrong[user] = users_psw[user]
del users_psw[user]
To_txt(users_psw, wrong)
while True:
users_psw, wrong = Read_txt()
user = input('请输入用户名:')
if user in wrong:
print(f'该账户{user}已锁定,不可用!')
break
elif user in users_psw.keys():
Check_user_psw(user)
else:
print('不存在该用户!')
break
# print(users_psw)
# print(wrong)
|