一旦我的文件中有了一个用户名,进程就会终止(Python)
如果我在users.csv文件中有一个用户名,整个程序运行正常,但只要添加了第二个用户名,repl(IDE)就会退出程序。我知道代码非常混乱和业余,但现在我只是想修复这一部分 需要修改的部分v一旦我的文件中有了一个用户名,进程就会终止(Python),python,authentication,Python,Authentication,如果我在users.csv文件中有一个用户名,整个程序运行正常,但只要添加了第二个用户名,repl(IDE)就会退出程序。我知道代码非常混乱和业余,但现在我只是想修复这一部分 需要修改的部分v def login(): existing = input("Do you already have a account? Y/N >" ).upper() if existing == "Y": pass else: print("Welcome to the regr
def login():
existing = input("Do you already have a account? Y/N >" ).upper()
if existing == "Y":
pass
else:
print("Welcome to the regristration page")
file = open("users.csv", "a+")
file.write("{}\n".format(input("What would you like your username to be? >")))
file.close()
login()
def auth_users():
username = input("What is your username?")
file = open("users.csv","r")
reader = csv.reader(file)
for record in reader:
if record[0] == username:
continue
else:
exit()
file.close()
auth_users()
整个计划
def login():
existing = input("Do you already have a account? Y/N >" ).upper()
if existing == "Y":
pass
else:
print("Welcome to the regristration page")
file = open("users.csv", "a+")
file.write("{}\n".format(input("What would you like your username to be? >")))
file.close()
login()
def auth_users():
username = input("What is your username?")
file = open("users.csv","r")
reader = csv.reader(file)
for record in reader:
if record[0] == username:
continue
else:
exit()
file.close()
auth_users()
运行程序时没有错误。无论哪种方式,无论用户是否存在于您的文件中,您的程序都将在没有输出的情况下结束 您可以尝试稍微改进一下:
def auth_users():
username = input("What is your username?")
file = open("users.csv","r")
reader = csv.reader(file)
for record in reader:
if record[0] == username:
print(f"Hello, {username}")
exit() # You found the guy, exit your program here
# Don't exit here: go through all the names until you find the guy (or not)
# End of the loop. We didn't find the guy.
print("You're not registered")
问题就在这里
for record in reader:
if record[0] == username:
continue
else:
exit()
您可能错误地使用了exit()
和continue
。当您想退出python的交互模式并引发SystemExit
异常时,通常会调用exit
函数(在这种情况下,会导致程序退出)<另一方面,code>continue告诉python继续循环中的下一步
您可能希望执行类似的操作:
for record in reader:
if record[0] == username:
# Handle authenticated users here
print("Login successful")
return # exit the function
# Handle unauthenticated users here
print("User not found")
您还应该考虑用上下文管理器替换文件的打开和关闭。而不是:
my_file = open("some-file", "r")
# read some input from the file
my_file.close()
# ...
my_file = open("some-file", "w")
# write some output to the file
my_file.close()
使用:
这样,即使在过程中遇到异常,python也会尝试关闭您的文件
with open("some-file", "r") as my_file:
# read my_file in here
# ...
with open("some-file", "w") as my_file:
# write to my_file in here