I am trying to build a basic login system in Python. I am saving the username and password inputs to a text file, but I am unsure how to most effectively validate them upon calling the login function.
How can I check to see if the username (user_variable) and password (pass_variable) are in the text file next to each other so as to let the user login?
Here is my login function.
def login():
user_varialbe = input("Username: ")
pass_variable = input("Password: ")
for line in open("userdata.txt", "r").readlines():
login_info = line.split(',')
# to test if they ar ebeing returned together in a list
print(login_info)
if user_varialbe == login_info[0] and pass_variable == login_info[1]:
print("Correct credentials!")
return True
else:
print("Incorrect credentials.")
return False
EDIT: When I run the code, here is the output. It's the username (alpha) and the password (111) with the \n.
['alpha', '111\n']
Incorrect credentials.
Here is the rest of the program.
def signup():
username = input("Username: ")
password = input("Password: ")
c_password = input("Confirm Password: ")
if password != c_password:
print("Passwords do not match. Please try again.")
signup()
print(f"Sign up success. Your username is '{username}'")
file = open('userdata.txt', 'a')
file.write(username + ',' + password)
file.write('\n')
file.close()
def start():
x = input("Login/Signup: L/S: ").lower()
if x == "l":
login()
elif x == "s":
signup()
else:
print('Please enter a valid answer')
start()