Python: How do I check if login and password int exist in a txt file?

Question:

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', '111n']
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()
Asked By: pc510895

||

Answers:

Since your file is a CSV, one option is to use csv.reader and look for a list with the appropriate values:

import csv

def login():
    with open('userdata.txt') as file:
        if [input("Username: "), input("Password: ")] in csv.reader(file):
            print("Correct credentials!")
            return True
        else:
            print("Incorrect credentials.")
            return False

Note that your signup function can use csv.writer as well, replacing:

    file = open('userdata.txt', 'a')
    file.write(username + ',' + password)
    file.write('n')
    file.close()

with:

    with open('userdata.txt', 'a', newline='') as file:
        csv.writer(file).writerow([username, password])
Answered By: Samwise
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.