Home > Back-end >  How can I check each line in a txt file for the right username and password
How can I check each line in a txt file for the right username and password

Time:03-30

The purpose of this task is to check each line in the user.txt file (that contains a list of usernames and passwords)

The program should then compare the input username and password to each line in the txt file if it doesn't find any matching username and password it displays an error message if it does the loop should break

user.txt
Steve steve123
Eddie ed123
Dexter dex123

I tried just about anything I could think of.

Although I'm almost dead certain the problem is in the loop.

It seems that it only compares the last line in the txt file

I'm still pretty new to this so please have mercy :)

Any tips on how I can get the program to check if the user input matches each individual line of text. Also , The txt file can change or be added to at any point , if not I could have accomplished this using line indexing.


content = ""
user_List = []


while True:

    print("Username")
    username = input()
    print("Password")
    password = input()
    name_pass = username   " "   password

    with open("user.txt" , "r ") as f:
        for line in f:
            if name_pass == line:
                
                x = False
            else:
                x = True

    if x == False:
        print("Wellcome")
        break
    elif x == True:
        print("Incorrect Username or Password \nPlease try again")


    

CodePudding user response:

The problem has to be that when you iterate over the line , the line will end up with an \n because in your txt file there is a return which is embeded without you see the \n! . To verify this you can add this statement « print(repr(line)) » after the « for line in f » statement. The repr function(representation) will show you the string without getting rid of the \n. And if this is the case you simply can verify like this : if name_pass == line[:-1], im pretty sure you understand this last statement ahah;)

CodePudding user response:

I changed the variable x, now it's called deny_access. Anyway, I think the problem is in the for loop. In your code you modify the variable x in every line, so after the for loop the only line that matters is the last. This was wrong. Here is how to fix the code:

content = ""
user_List = []


while True:

    print("Username")
    username = input()
    print("Password")
    password = input()
    name_pass = username   " "   password

    with open("user.txt" , "r ") as f:
        deny_access = True
        for line in f:
            if name_pass == line:
                deny_access = False
                break

    if deny_access == False:
        print("Wellcome")
        break
    elif deny_access == True:
        print("Incorrect Username or Password \nPlease try again")

Note: With this fix it should work. But that doesn't mean it's safe or that it's a good programming practice. What I mean is that if this is a code that you are testing things to learn or a small project, it is perfect. But if it goes to production or something bigger, you have to change a bunch of things.

CodePudding user response:

firs of all each line in the text file ends with a new line so for name_pass variable to match u need to add new line to the end of it

name_pass = username " " password "\n"

second the logic of the if statements is not right u need to break the loop after u find a match so the x doesn't get overwrite again with false value

    with open("user.txt", "r ") as f:
    for line in f:
        if name_pass == line:
            x = False
            break
        else:
            x = True

CodePudding user response:

here you are, man. try this. I always do that in this condition. if you are trying to simulate something like login page, you can use this code as a sample. also you can see examples of using text files to save password in similar conditions.

import os
import shutil
def action():
    action = int(input("what you want to do?\n1 for create account\n2 for delete existed account\n: "))
    if action == 1:
        signup()
    elif action == 2:
        delete_account()
    else:
        print("no valid option has been selected")

def delete_account():
    username = input("enter your username: ")
    password = input("enter your password: ")
    if os.path.isdir(f"./{username}_account"):
        with open(f"./{username}_account/password", 'r') as passfile:
            pass_containment = passfile.read()
        if password == pass_containment:
            shutil.rmtree(f"./{username}_account")
            print("your account has been removed")
        else:
            print("username or password is not correct")
    else:
        print("username or password is not correct")

def signup():
    username = input("set a username: ")
    password = input("set a password: ")
    conf_password = input("confirm your password: ")
    if username == password:
        print("password and username cannot be same")
    else:
        if os.path.isdir(f"./{username}_account"):
            print("account has been already existed, choose another username")
        else:
            if password == conf_password:
                os.mkdir(f"{username}_account")
                with open(f"./{username}_account/username", 'w') as userfile:
                    userfile.write(username)
                with open(f"./{username}_account/password", 'w') as passfile:
                    passfile.write(str(password))
            else:
                print("passwords are not same")
action()
  • Related