1 def menu():
2 #用户交互界面
3 user_name = input("请输入在用户名:")
4 password = input("请输入密码:")
5 return user_name,password #以元组形式返回值
6 '''
7 alex1 1111
8 alex2 2222
9 alex3 3333
10 '''
11 def write():
12 #将用户名、密码和登录次数在文件中写成字典的格式
13 user_name_password= {}#设置一个空字典装用户名、密码和登录次数
14 with open("test", encoding="utf8") as date, open("test2", encoding="utf8", mode="w") as revise:
15 for line in date:
16 line1 = line.strip().split() #以空格分隔后是列表形式
17 user_name_password.setdefault(line1[0],[line1[1],0])#key值为用户名,value值为[密码,登录次数]
18 user_name_password = str(user_name_password) #将字典转换成字符串
19 revise.write(user_name_password) #将字典转换成的字符串写入文件test2
20
21
22 def main():
23 write()
24 while True:
25 res = menu()#用户名和密码输入,返回值为元组形式(用户名,密码)
26 with open("test2",encoding="utf8") as date:
27 user_name_password = {} #创建一个空字典,接收用户、密码和登录次数的的数据
28 for line in date:
29 user_name_password = eval(line) #将用户、密码和登录次数数据转化为字典
30 if res[0] in user_name_password and user_name_password[res[0]][1] == 3:
31 #文件中登录名已记录三次,禁止登录
32 print("登录次数过多锁定")
33 break
34 if res[0] in user_name_password and res[1] in user_name_password[res[0]][0] and user_name_password[res[0]][1] < 3:
35 #用户、密码匹配成功和登录次数小于三次,登录成功
36 print("successful")
37 break
38 if res[0] in user_name_password and res[1] not in user_name_password[res[0]][0]:
39 #用户匹配,密码不匹配,拉入黑名单,登录次数+1
40 user_name_password[res[0]][1]=user_name_password[res[0]][1]+1 #登录次数+1
41 user_name_password.setdefault(res[0],user_name_password[res[0]][1]) #将字典中登录次数的信息进行修改
42 user_name_password = str(user_name_password) #将字典转换成字符串
43 with open("test3", encoding="utf8", mode="w") as revise:
44 revise.write(user_name_password) #匹配不成功,将信息写入文件
45 date.close() #改文件名需关闭文件
46 revise.close() #关闭文件需关闭文件
47 import os
48 os.rename("test2", "test_bak")
49 os.rename("test3", "test2")
50 os.remove("test_bak") #删除费文件
51 print("用户名或者密码错误,请重新输入")
52 else:
53 print("用户名或者密码错误,请重新输入")
54 main()