用户登录验证,输入密码错误三次,锁定此用户。 将用户信息存入文件
文件内容格式如下:
{'username':'heilong','password':'123456','login_flag':True} {'username':'dong','password':'23456','login_flag':True} {'username':'bin','password':'3456','login_flag':False} {'username':'dun','password':'456','login_flag':False} {'username':'ke','password':'56','login_flag':False}
1 import os 2 3 file_ismodify = False 4 5 username_in = input("请输入用户名:") 6 with open("login_lock", "r", encoding="utf-8") as read_file, \ 7 open("login_lock_new", "w", encoding="utf-8") as write_file: 8 for line in read_file: 9 if eval(line)["username"] == username_in: 10 if eval(line)["login_flag"]: 11 print("您的账号被锁定,拒绝登录!") 12 break 13 else: 14 count = 0 15 while count < 3: 16 password_in = input("请输入密码:") 17 if eval(line)["password"] == password_in: 18 print("登录成功!") 19 break 20 else: 21 if count != 2: 22 print("登录失败,您还有%s次机会" % (2 - count)) 23 else: 24 print("三次输入用户名或密码错误,拒绝登录!") 25 write_file.write("{'username':'%s','password':'%s','login_flag':%s}\n"\ 26 %(username_in,eval(line)["password"],True)) 27 file_ismodify = True 28 break 29 count += 1 30 else: 31 write_file.write(line) 32 33 if file_ismodify: 34 os.rename("login_lock","login_lock.bak") 35 os.rename("login_lock_new","login_lock") 36 os.remove("login_lock.bak") 37 else: 38 os.remove("login_lock_new")