python用户登录注册 文件读写 指针运用

# -*- coding: utf-8 -*-

from os.path import isfile


class User:
    def __init__(self, username, passwd, file_info):
        self.user = username
        self.pwd = passwd
        self.file_db = file_info

    def file_oper(file, mode, *args):
        if mode == 'a+':
            data = args[0]
            with open(file, mode) as f:
                f.write(data)
        elif mode == 'r':
            with open(file, mode) as f:
                data = f.read()
                return data

    # 该部分要求实现注册功能,要异常捕获实现注册成功,出错,及用户名已存在提示
    def regist(self):
        list_user = []
        if isfile(self.file_db):
            with open(self.file_db, 'r') as f:
                for line in f:
                    username = line.strip().split(':')[0]
                    list_user.append(username)
        if self.user not in list_user:
            try:
                with open(self.file_db, 'a+') as f:
                    user_info = '%s:%s\n' %(self.user, self.pwd)
                    f.write(user_info)
                print('\033[32;1m注册成功。\033[0m')
            except Exception as e:
                print('Error: ', e)
        else:
            print('\033[31;1m该用户已存在.\033[0m')


    def login(self):
        list_user = []
        u_list = '%s:%s' %(self.user, self.pwd)
        with open(self.file_db, 'r') as f:
            for line in f:
                list_user.append(line.strip())
        if u_list in list_user:
            print('\033[32;1m登录成功.\033[0m')
        else:
            print('\033[31;1m用户名或密码错误.\033[0m')







def start():
    while True:
        print('1. 注册\n'
              '2. 登录\n'
              '3. 退出')
        choice = input('>>>').strip()
        if choice.isdigit() and 0 < int(choice) < 4:
            if choice == '1':
                username = input('用户名:').strip()
                passwd = input('密码:').strip()
                user = User(username, passwd, 'user.db')
                user.regist()
            elif choice == '2':
                username = input('用户名:').strip()
                passwd = input('密码:').strip()
                user = User(username, passwd, 'user.db')
                user.login()
            elif choice == '3':
                break
        else:
            print('输入错误.')


if __name__ == '__main__':
    start()


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值