1

I'm on a coding course and am struggling with a task.

I have a txt file that I'm importing data from (in this case usernames and passwords). The first line (and only provided to start with) is: admin, adm1n Logging in with this is fine. Once I've added a 2nd user and password though only the new user works to log in and the admin one no longer works.

So for the below code, my txt now reads:

admin, adm1n

user2, password

file = open("user.txt", "r")

user = file.readlines()
for line in user:
    data = line.split(", ")

user_username = data[0]
user_password = data[1]

while username != user_username:
    username = input("Sorry, that username is not recognised, please try again: ")

else:
    password = input("Please enter your password: ")
    
    while password != user_password:
        password = input("Sorry, that password is not recognised, please try again: ")

    else:
        print("\nThank you. Logging in...\n")

In case it's relevant, I've added the new login details in the below way:

while True:
    menu = input('''Select one of the following Options below:
r - Registering a user
a - Adding a task
va - View all tasks
vm - view my task
e - Exit
: ''').lower()

    if menu == 'r':
        new_user = input("Please enter a new username: ")
        new_password = input("Please enter a new password: ")
        password_confirmation = input("Please confirm your password: ")          
        while new_password != password_confirmation:
            new_password = input("Sorry, those did not match. Please enter a new password: ")
            password_confirmation = input("Please confirm your password: ")
        
        with open("user.txt", "a") as file: 
            file.write("\n" + new_user + ", " + new_password)

The above all works but I can no longer use admin as a login, only user2 once entered.

Thanks in advance for any help - please let me know if I need to clarify anything! I'm a beginner so if you can explain where I'm going wrong as well as the code I should be using so I can learn I'd really appreciate it!

mandykg
  • 33
  • 4
  • `data = line.split(", ")` overwrites `data` every next iteration, so after loop finished you will have just value of last line splitted stored in `data`. – Olvin Roght Dec 29 '22 at 17:51
  • ok thanks, what should I use instead of data = line.split(", ") then please? – mandykg Dec 30 '22 at 10:26
  • You can make `data` a `list` and append pairs to it. But I'd recommend you to proceed with `dict` where username is a key and password is a value, it'll fit better there. – Olvin Roght Dec 30 '22 at 10:52

0 Answers0