OSG
OSG

Reputation: 67

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 external text file (accountfile.txt), but when it comes to the login I have no idea how to get the program to check if what the user inputs is present in the text file.

This is what my bit of code looks like :

def main():
    register()

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.close()
    login()

def login():
    check = open("accountfile.txt","r")
    username = input("Please enter your username")
    password = input("Please enter your password")

I have no idea what to do from this point.

Also, this is what a registered account would look like in the text file:

Ha2001 examplepassword

Upvotes: 1

Views: 46463

Answers (1)

Brenden Petersen
Brenden Petersen

Reputation: 2022

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

Upvotes: 2

Related Questions