pythonwhile-loopnotinexternal-data-source

How to fix while loop problem reading from txt file


Could someone lend some advice on the current problem I am having. I am writing a program to assign tasks to specific users. All the users are stored on an external txt file. What Id like to do is even though I am logged into the program as one user I'd like to enter the username of another user and assign tasks to them. The problem I am having is when I ask the user to input the username of the person they want to assign the task to its only finding the last username in the txt file. Its returning the error message I wrote if the name is not present. Its only finding the last user in the txt file

The txt file is as follows:

admin, adm1n

bobby, bobby1

jake, jake1

i.e - admin is the user name in the txt file and adm1n the password

The code is only accepting the last username jake and not finding the others and as I add more users its only finding the last one added.

My code is as follows:

with open ('user.txt', 'a')as username:
     task = input("Please enter the username of the person the task is assigned to.\n")
            while task not in username:
                task = input("Username not registered. Please enter a valid username.\n")

Solution

  • The correct code would be:

    with open( 'user.txt' ) as fin :
        usernames = [i.split(',')[0] for i in fin.readlines() if len(i) > 3]
    
    task = input ('...' )
    while task not in usernames :
        task = input( ' ... ' )
    

    I did not copy the messages, you may do it yourself.