Trouble with making a login function in python

420 Views Asked by At

Hello I am a student and I have been researching on here for way too long to find answers to how to make this login page actually work. All the pages I have found have made them in different ways that don't work for me. Can anyone off this code push me on the right track to create this. I have got my signup page to work though.

def signup():
    
    users = open("login_signup.txt","a")
    user = []
    username = input("What do you want your username to be?: ")
    password = input("What do you want your password to be?: ")
    user.append(username)
    user.append(password)
    users.write(username + "," + password)
    users.write("\n")

    print("You have successfully signed up")


def login():
    
    with open("login_signup.txt","r") as users:
        
        usersusername = input("What is your username?: ")
        userspassword = input("What is your password?: ")

Btw the format off the text in the file is: username,password

Then it goes to a new line after the next person wants to create an account.

Thanks to anyone who can help :)

1

There are 1 best solutions below

1
DarrylG On BEST ANSWER

Since you're still having problems here's a modification of your code that works.

def signup():
    
    with open("login_signup.txt","a") as users: # context manager is preferred over pure open/close
        #user = []                              # not used so remove
        username = input("What do you want your username to be?: ")
        password = input("What do you want your password to be?: ")
        #user.append(username)                  # not used so remove
        #user.append(password)                  # not used so remove
        users.write(username + "," + password)
        users.write("\n")

        print("You have successfully signed up")


def login():
    
    usersname = input("What is your username?: ")
    userspassword = input("What is your password?: ")
  
    with open("login_signup.txt", "r") as users:

        for line in users:                              # iterating over login file a line at a time
            login_info = line.rstrip().split(',')       # rstrip() removes the '\n' at end of string
                                                        # split(',' split string on comma 
            if usersname == login_info[0] and userspassword == login_info[1]:
                print("Correct credentials!")
                return True
        
    print("Incorrect credentials.")
    return False

Exmaple Run

sigup()
# Out:
#     What do you want your username to be?: john
#     What do you want your password to be?: paul
#     You have successfully signed up


login()
# Out:
#    What is your username?: john
#    What is your password?: paul
#    Correct credentials!
#    True