首页 > 解决方案 > 如何修复在写入文件后重新启动自身 3 行的函数?

问题描述

我正在使用 csv 库创建一个简单的登录脚本,以实现我自己的教育价值。当我使用该功能时,register();在将登录详细信息附加到文件后,我的代码似乎在第 63 行重新启动:

password = input('Please enter your chosen password: ')

我试图找到一个类似的问题(没有成功),我猜测这与我的结构有关。

# login.py
""" Logs in reading from a CSV
    text file
    """

# Imports
import csv

# Functions
def reset_login_file():
    """ Resets the users.txt
        file
        """

    with open('users.txt', 'w', newline='') as csvfile:
        csv_writer = csv.writer(csvfile)

        csv_writer.writerow(['Admin', 'password'])

def login():
    """ Checks users.txt and
        logs in
        """

    print('')

def check_for_name(name_chosen):
    """ Checks for name_chosen in
        users.txt
        """

    with open('users.txt', 'r', newline='') as check_csvfile:
        csv_reader = csv.reader(check_csvfile)

        for row in csv_reader:
            if row[0] == name_chosen:
                print('Name is taken, please try again!')
                register()
                break

def password_checker(password_chosen):
    """ Checks the password
        meets criteria
        """

    stop_loop = False
    while not stop_loop:
        if len(password_chosen) > 6 and len(password_chosen) < 13:
            print('Valid Password!')
            stop_loop = True
        else:
            print('Invalid Password, please try again!')
            register()
        break

def register():
    """ Registers the user in
        users.txt
        """

    username = input('Please enter your chosen username: ')
    check_for_name(username)
    password = input('Please enter your chosen password: ')
    password1 = input('Please re-enter your chosen password: ')
    if password == password1:
        password_checker(password)
    else:
        print('Please try again!')
        register()

    print('Creating your account!')
    with open('users.txt', 'a', newline='') as csvfile:
        csv_writer = csv.writer(csvfile)

        csv_writer.writerow([username, password])

# Code here - Interactive loop
stop = False
while not stop:
    print('Welcome!\nTo view commands, please press Enter!')
    input()
    print("""COMMANDS
    Reset Login File [RLF]
    Register [R]
    Login    [L]
    Quit     [Q]
          """)
    choice = input('Select a Command: ')

    if choice == 'r':
        register()
    elif choice == 'rlf':
        reset_login_file()
    elif choice == 'l':
        login()
    elif choice == 'q':
        stop = True
    else:
    print('Choose a valid command')

来自外壳的文本:

Welcome!  
To view commands, please press Enter!

COMMANDS  
    Reset Login File [RLF]  
    Register [R]  
    Login    [L]  
    Quit     [Q]  

Select a Command: r  
Please enter your chosen username: fred  
Name is taken, please try again!  
Please enter your chosen username: red  
Please enter your chosen password: bobsred  
Please re-enter your chosen password: bobsred  
Valid Password!  
Creating your account!  
Please enter your chosen password: redhead  
Please re-enter your chosen password: redhead  
Valid Password!  
Creating your account!  
Welcome!  
To view commands, please press Enter!

users.txt 内容如下:

Admin,password  
bob,password  
fred,password  
red,bobsred  
fred,redhead  

我希望这已经注册了用户,然后返回到交互式循环。

标签: pythonpython-3.xcsv

解决方案


您会看到递归调用来register()放松并从中断的地方继续。

有帮助的一件事是设计帮助函数以True在一切正常或False用户需要重试时返回。然后在内部使用循环register()来根据需要多次调用它们。

这是一个例子:

# login.py
""" Logs in reading from a CSV
    text file
    """

# Imports
import csv

# Functions
def reset_login_file():
    """ Resets the users.txt
        file
        """

    with open('users.txt', 'w', newline='') as csvfile:
        csv_writer = csv.writer(csvfile)

        csv_writer.writerow(['Admin', 'password'])

def login():
    """ Checks users.txt and
        logs in
        """

    print('')

def check_for_name(name_chosen):
    """ Checks for name_chosen in
        users.txt
        """

    with open('users.txt', 'r', newline='') as check_csvfile:
        csv_reader = csv.reader(check_csvfile)

        for row in csv_reader:
            if row[0] == name_chosen:
                print('Name is taken, please try again!')
                return False
    return True

def password_checker(password_chosen):
    """ Checks the password
        meets criteria
        """

    if len(password_chosen) > 6 and len(password_chosen) < 13:
        print('Valid Password!')
        return True
    else:
        print('Invalid Password, please try again!')
        return False

def register():
    """ Registers the user in
        users.txt
        """

    while True:
        username = input('Please enter your chosen username: ')
        if check_for_name(username):
            break
    while True:
        password = input('Please enter your chosen password: ')
        password1 = input('Please re-enter your chosen password: ')
        if password == password1:
            password_checker(password)
            break
        else:
            print('Please try again!')

    print('Creating your account!')
    with open('users.txt', 'a', newline='') as csvfile:
        csv_writer = csv.writer(csvfile)

        csv_writer.writerow([username, password])

# Code here - Interactive loop
stop = False
while not stop:
    print('Welcome!\nTo view commands, please press Enter!')
    input()
    print("""COMMANDS
    Reset Login File [RLF]
    Register [R]
    Login    [L]
    Quit     [Q]
          """)
    choice = input('Select a Command: ')

    if choice == 'r':
        register()
    elif choice == 'rlf':
        reset_login_file()
    elif choice == 'l':
        login()
    elif choice == 'q':
        stop = True
    else:
        print('Choose a valid command')

推荐阅读