文件中只有一个用户名后,该过程就会终止(Python)

如果我在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 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","r")
  reader = csv.reader(file)
  for record in reader:
    if record[0] == username:
      continue
    else:
      exit()
  file.close()
auth_users()
wangzhenhxy 回答:文件中只有一个用户名后,该过程就会终止(Python)

运行程序时没有错误。无论哪种方式,无论用户是否存在于您的文件中,您的程序都将结束而不会输出。

您可以尝试改善一些地方:

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的交互模式时,通常会调用exit函数,并引发SystemExit异常(在这种情况下会导致程序退出)。另一方面,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()

使用:

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

通过这种方式,即使在执行过程中遇到异常,python也会尝试关闭文件。

本文链接:https://www.f2er.com/3166287.html

大家都在问