Как только у меня есть одно имя пользователя в моем файле, процесс умирает (Python) - PullRequest
0 голосов
/ 04 ноября 2019

Вся программа работает нормально, если у меня есть одно имя пользователя в файле 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()

Ответы [ 2 ]

0 голосов
/ 04 ноября 2019

Вот проблема

for record in reader:
  if record[0] == username:
    continue
  else:
    exit()

Вы, вероятно, ошибаетесь в использовании exit() и continue. Функция exit обычно вызывается, когда вы хотите выйти из интерактивного режима 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 пытается закрыть ваш файл, даже если на пути встречается исключение.

0 голосов
/ 04 ноября 2019

Нет ошибки при запуске вашей программы. В любом случае, независимо от того, существует ли пользователь в вашем файле или нет, ваша программа завершится без вывода.

Вы можете попытаться немного улучшить ситуацию:

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")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...