创建程序以模拟登录功能

时间:2017-03-10 04:24:16

标签: python python-3.x file io credentials

我正在尝试创建一个登录程序,将用户的输入凭据与存储在文本文件中的凭据进行比较 我该如何正确地做到这一点?

这是我到目前为止所做的:

file = open("logindata.txt", "r")   
data_list = file.readlines()   
file.close()   
print(data_list)   


for i in range(0, len(data_list)):   
        username = input("username: ")           
        password = input("password: ")      
        i += 1  
        if i % 2 == 0:   
            if data_list[i] == username and data_list[i + 1] == password:   
            print("You are successfully logged in as", username)  
            i == len(data_list)  
        elif data_list[i] == username and data_list[i + 1] != password:   
            print("The password you entered was incorrect, please try again.")    
        else:   # how do i end the code if the user inputs no
            if data_list[i] != username:   
                choice = input("The username you entered was not found, would you like to create an account? (Y/N)")   
                if choice.upper() == "Y":    
                    new_username = input("new username: ")    
                    data_list.append(new_username + "\n")     
                    new_password = input("new password: ")     
                    data_list.append(new_password + "\n")    
                    file = open("logindata.txt", "w")    
                    file.writelines(data_list)    
                    i == data_list    

这是凭证文本文件的设置方式:

user1
pass1
user2
pass2

1 个答案:

答案 0 :(得分:1)

我想你想要这样的东西:

def does_username_exists(username, login_file_path):
  username_exists = False
  user_password = None
  with open(login_file_path) as login_file:
    while True:
      username_line = login_file.readline()
      if not username_line: break
      password_line = login_file.readline()
      if not password_line: break
      if username == username_line.strip():
        username_exists = True
        user_password = password_line.strip()
        break

  return username_exists, user_password


def main():
  login_file_path = "logindata.txt"

  username = input("Enter username: ")
  username_exists, user_password = does_username_exists(username, login_file_path)
  if not username_exists:
    choice = input("The username you entered was not found, would you like to create an account? (Y/N)")
    if choice.upper() == 'Y':
      new_username = input("Enter new username: ")
      new_password = input("Enter new password: ")
      with open(login_file_path, "a") as login_file:
        login_file.write(new_username + "\n")
        login_file.write(new_password + "\n")
    return

  password = input("Enter password: ")
  if not (password == user_password):
    print("The password you entered was incorrect, please try again.")
  else:
    print("You are successfully logged in as - '{}'".format(username))


if __name__ == "__main__":
  main()