python3 用戶登錄注冊(函數,文件操作實現)


#!/usr/bin/env python
# -*- coding:utf-8 -*-

#用函數和文件操作實現用戶登錄與用戶注冊
def login(username,password):
    """
    此函數用於用戶登錄驗證
    :param username:用戶名
    :param password:密碼
    :return:True 表示用戶驗證成功,False 表示用戶驗證失敗
    """
    with open("login.txt","r",encoding="utf-8") as f:
     for line in f:
        #默認strip無參數:刪除字符串左右兩邊的空格或者換行符
        #有參數:刪除兩側指定的值
        line_new=line.strip()
        #指定分隔符對字符串進行切片,最終輸出一個列表
        line_list=line_new.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("login.txt","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("login.txt", "r", encoding="utf-8") as f:
        for line in f:
            line_new=line.strip()
            line_list=line_new.split("&")
            if username==line_list[0]:
                return True
    return False

#定義一個主函數,執行操作
def main():
 print("歡迎登錄XXX系統")
 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":
     user = input('請輸入用戶名:')
     pwd = input('請輸入密碼:')
     is_exist=user_exist(user)
     if is_exist:
         print("該用戶已注冊")
     else:
         result=register(user,pwd)
         if result:
             print("注冊成功")
         else:
             print("注冊失敗")

main()
View Code

 







免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM