繁体   English   中英

一旦我的文件中有一个用户名,进程就会终止(Python)

[英]Once I have one username in my file, the process dies (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", "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()

运行程序时没有错误。 无论哪种方式,无论用户是否存在于您的文件中,您的程序都将在没有 output 的情况下结束。

您可以尝试改进一下:

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 exit function 通常在您想要退出 python 的交互模式并引发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 会尝试关闭您的文件,即使在此过程中遇到异常也是如此。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM