How To Check Text File For Usernames And Passwords
I'm writing a program which will need a user to register and login with an account. I get the program to have the user make their username and password which are saved in an extern
Solution 1:
After opening the file, you can use readlines()
to read the text into a list of username/password pairs. Since you separated username and password with a space, each pair is string that looks like 'Na19XX myPassword'
, which you can split into a list of two strings with split()
. From there, check whether the username and password match the user input. If you want multiple users as your TXT file grows, you need to add a newline after each username/password pair.
def register():
username = input("Please input the first 2 letters of your first name and your birth year ")
password = input("Please input your desired password ")
file = open("accountfile.txt","a")
file.write(username)
file.write(" ")
file.write(password)
file.write("\n")
file.close()
if login():
print("You are now logged in...")
else:
print("You aren't logged in!")
def login():
username = input("Please enter your username")
password = input("Please enter your password")
for line in open("accountfile.txt","r").readlines(): # Read the lines
login_info = line.split() # Split on the space, and store the results in a list of two strings
if username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
return True
print("Incorrect credentials.")
return False
Post a Comment for "How To Check Text File For Usernames And Passwords"