作业 7.15

编写登录功能,能登录多个用户,从文件中比对用户名和密码,同一个账号输错3次将被锁定300秒
账户文件为user.txt
从左往右依次是: 用户名:密码:输错计数:解除锁定的时间(初始默认为0)
内容如下:

cc:111:0:0
jason:222:0:0
jack:333:0:0
lily:444:0:0

程序如下:

import os
import time

user_list = []
with open('user.txt', mode='r', encoding='utf-8') as f:
    for line in f:
        name, *_ = line.strip('\n').split(':')
        user_list.append(name)

tag = True
while tag:
    print(user_list)
    inp_name = input("请输入你的用户名:").strip()  # 判断用户名是否存在
    if inp_name in user_list:
        with open('user.txt', mode='rt', encoding='utf-8') as f1, \
                open('new_info.txt', mode='wt', encoding='utf-8') as f2:

            for line in f1:
                if inp_name in line:
                    old_line = line
                    old_user = line.strip('\n').split(':')
                    count = int(old_user[2])
                    now_time = time.time()

                    if now_time > float(old_user[3]):
                        inp_pwd = input("请输入你的密码:").strip()
                        if inp_pwd == old_user[1]:
                            print('登录成功!')
                            f1.seek(0, 0)  # 调到文件开头重新读
                            data = f1.read()
                            f2.write(data)  # 创建一个新文件复制写入user.txt的全部内容
                            tag = False
                            break  # 退出for循环执行覆盖操作
                        else:
                            print('密码错误')
                            now_time = time.time()
                            count += 1
                            old_user[2] = str(count)
                            if count == 3:
                                lock_time = now_time + 300  # 当前时间往后顺延300秒,记录到文件中,更改原时间
                                old_user[3] = str(lock_time)

                            new_line = ':'.join(old_user) + '\n'
                            f1.seek(0, 0)  # 指针跳到开头
                            data = f1.read()

                            res = data.replace(old_line, new_line)
                            f2.write(res)
                            break

                    else:
                        print('当前用户输入错误超过3次,已经被锁定,请稍后再试')
                        continue  # 不执行下面的覆盖文件操作

        os.remove('user.txt')
        os.renames('new_info.txt', 'user.txt')

    else:
        print('用户名不存在,请重新输入')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值