如何使程序继续在文件中搜索另一个用户名?

我正在尝试在Repl.it中完成我的代码在Python中的登录过程。它将搜索名为“ UDfile”的csv文件以确认用户名和密码,以便随后可以访问我正在创建的纸牌游戏。该文件的外观如下:

markd,12345
pltwo,67890
forhb,10\/3

但是,我正在为2个用户创建此文件。只要我输入的用户名高于第二个用户名,登录第一个用户就可以正常工作。但是,当我尝试输入第二个用户名(正确与否)时,总是会说它无法识别用户名。我怀疑它无法完全搜索。我如何才能彻底搜索该csv文件,以便它允许我输入P2的密码并继续执行该程序?

我正在沿着“如何获取此代码以在现有用户名不存在时找到它的代码?”的名称搜索堆栈溢出。但是我找不到任何东西。

我也尝试添加

sys.exit

的结尾

print(“找不到用户名”)

user_findtwo(文件,用户)中的文件,希望它能彻底搜索文件并仅在完全找不到文件时才终止,但是在程序说一次找不到文件后,它将立即结束代码。

最后,我尝试了一个while循环说

while row[0] != usertwo:
 print("username not found")
sys.exit()

我希望它会搜索整个文本文件并说“找不到用户名”,直到找到玩家二的用户名为止,而只是不断地打印“找不到用户名”。

import csv
import sys

def main():
  login()
  logintwo()
  show_menu()
  menu_choice = int(input("Welcome to the RYG card game! Press \"1\" and then \"Enter\" to play a game:"))
  options(menu_choice)

def login(): 
  with open("UDfile","r") as file:
    file_reader = csv.reader(file)
    user_find(file_reader)
    file.close

def user_find(file):
  user()
  for row in file:
   if row[0] == user:
    print("username is found:",user)
    user_found = [row[0],row[1]]
    pass_check(user_found)
    break
  else:
      print("username not found")
      sys.exit()

def user():
  global user
  user = input("Player 1,enter your username (must be above player 2's desired name):")

def logintwo():
  with open("UDfile","r") as file:
    file_reader = csv.reader(file)
    user_findtwo(file_reader,user)
    file.close

def user_findtwo(file,user):

  usertwo = input("Player 2 enter your name:")
  if usertwo == user:
    print("usernames must be different. Restart the program.")
    sys.exit()
  else:
   for row in file:
      if row[0] == usertwo:
       print("username is found:",usertwo)
       user_found = [row[0],row[1]]
       pass_checktwo(user_found)
       break
      else:
         print("username not found")

def pass_check(user_found):
  x = True
  while x:
   user = input("Enter your password:")
   if user_found[1] == user:
    print("Password match.")
    x = False
   else:
    print("Password doesn't match.")
    sys.exit()

def pass_checktwo(user_found):
  y = True
  while y:
    usertwo = input("Player 2 enter your password:")
    if user_found[1] == usertwo:
      print("Password match.")
      y = False
    else:
      print("Password doesn't match.")
      sys.exit()

请参阅背景了解预期和实际结果。

jrr1234567 回答:如何使程序继续在文件中搜索另一个用户名?

您可以使用此方法遍历所有行吗?您可以使用len(csvFileArray)来获取长度,将其循环到最大长度以避免索引超出范围,并且一旦找到所需的内容就可以通过该函数(因此以后不继续循环?)

https://stackoverflow.com/a/39629619

只是快速思考

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

大家都在问