python 加载txt文本实现登录

来源:互联网 发布:电商部门美工 编辑:程序博客网 时间:2024/06/10 19:30
#Author:J.F.yang#Mail:guisii@126.com#例子有两个文本,一个是禁止登录的用户,forbid_users.txt# 一个是已注册的用户registered_users.txt(文本内容 用户名:字典),这个文本需要手动加入用户名密码,两者以":"分割#用户名正确,但密码输入错误三次,则该用户被添加至禁止登录的用户import getpass  #输入时,不以明文显示print("欢迎登录大爷要吃大侠麻辣烫")count =0username = input("username:")#读取用户名和密码,以字典方式赋值变量def registered_load_dict():    _dict = {}    filename='registered_users.txt'    try:        with open('registered_users.txt', 'r') as registered_users:            for reg_users in registered_users:                (key, value) = reg_users.strip().split(':')   #读取的文本中,以":"分割开,左边是key,右边是value                _dict[key] = value  #写入字典    except IOError as ioerr:        print("文件 %s 不存在" %filename)    return _dict'''#用户注册def registered_save_dict(_dict, filepath):    try:        with open(filepath, 'a+') as dict_file:            for (key, value) in _dict.items():                dict_file.write('%s:%s\n' % (key, value))    except IOError as ioerr:        print("文件 %s 无法创建" %filepath)'''#禁止用户 文本with open(r'forbid_users.txt', 'r') as forbid_users:    f_users = forbid_users.readlines()user_error = True   #用户是否已注册user_forbid = False  #用户是否被禁止登录#遍历禁止用户 文本for f_user in f_users:  #遍历用户禁止文本,获取用户名    if f_user.strip() == username.strip():  #用户输入与禁止登录文本比较        print("%s用户已被禁止登录" % username)        user_forbid = True   #条件成立,user_forbid=True        break        #遍历 已注册用户文本if  not user_forbid:  #如果上一个for循环嵌套的if条件成立,这里not True,则不执行下面的语句    for reg_user,password in registered_load_dict().items():  #遍历字典,dict.items()key是用户名,value是密码        if reg_user.strip() == username.strip(): #            while True:                input_password = getpass.getpass("password:")                if password == input_password:                    print("login success!Welcome!", username)                    break #跳出while循环                else:                    print("password error!,Try again")                    count += 1                    if count == 3:                        print("用户名或密码连续输错三次,终止登录")                        forbid_list.append(username)                        print("用户%s已被禁止登录!" % username)                        forbid_users = r'E:\week1\20170721day1\forbid_users.txt'                        with open(forbid_users, 'a+') as forbid_users:                            forbid_users.write(username+'\n')                        break  #跳出while循环            break  #if reg_user.strip() == username.strip():结束,跳出for循环    if  not user_error:  #如果遍历reg_users中未找到匹配用户,则执行  user_error = false        print("该用户未注册!")
原创粉丝点击