Python之简单的用户登录和注册
#!/bin/bash/env python # -*- coding:utf-8 -*- def login(username,password): """ 用于用户名密码的登录 :param username: 用户名 :param password: 密码 :return: True,用户验证成功;False,验证失败 """ with open('cai.log','r',encoding="utf-8") as f: for line in f: #一行一行的读取 line = line.strip() #去除两端的空格及换行符 line_list = line.split("$") #以$符号进行分割 if username == line_list[0] and password == line_list[1]: return True return False def register(username,password): """ 注册用户 :param username: 用户名 :param password: 密码 :return: True,注册成功 """ with open('cai.log',"a",encoding="utf-8") as f: temp = "\n" + username + "$" +password f.write(temp) return True def user_exist(username): """ 检查用户是否已经存在 :param username: 用户名 :return: True,则用户名已经存在;False,用户名不存在 """ with open('cai.log',"r",encoding="utf-8") as f: for line in f: line = line.strip() line_list = line.split("$") if username == line_list[0]: return True return False def main(): print("欢迎登陆瑞的系统") inp = input("1: 登陆;2: 注册") user = input("请输入用户名:") pwd = input("请输入密码:") if inp == "1": is_login = login(user,pwd) if is_login: print("登录成功") else: print("登录失败") elif inp == "2": is_exist = user_exist(user) if is_exist: print("用户已经存在,无法注册") else: result = register(user,pwd) if result: print("注册成功") else: print("注册失败") main()