0

I am working on a python project in which I use a while loop. Unique stuff. However, I can't get the loop to do its job for me.

My code:

with open("accounts.txt", "r") as account_file:
    while account == "":
        account = str(input("Enter a username: ") + " ")
        if account not in account_file.read():
            print("That username was not found.")
            account = ""

When I run this, it will prompt me to enter a username and if the string I entered (plus an added space) can be found in accounts.txt I will be told that my username can be found.

If I enter an invalid username, the program is supposed to tell me that it couldn't find the username I entered and then let me try again - except if I enter the username correctly on the next try, the program still tells me my username can't be found.

I tried making this change:

if account in account_file.read():
    account = account
else:
    print("That username was not found.")
    account = ""

And it still wouldn't work properly.

Can anyone tell me why?

I'm just looking for a simple solution.

  • Matt had a fine answer below. But also consider that in your first effort you're opening `account_file` once and then reading (i.e. consuming) it in every loop iteration. Unless you jump through special hoops - which you haven't - you can only `.read()` a file once. – Kirk Strauser Aug 24 '20 at 22:42
  • 1
    @KirkStrauser Good catch! I'll update my answer. – Matt Aug 24 '20 at 22:46

1 Answers1

1

When I originally answered your post I assumed that you wanted to find the line of the file on which the username is located in the file. If you're not interested in finding the specific line on which the username is located and just want a loop that continues until a valid username is entered then you should know that you can only call read() on a file once after opening.

Consider doing this:

while account == "":
    account = str(input("Enter a username: ") + " ")
    with open("accounts.txt", "r") as account_file:
        if account not in account_file.read():
            print("That username was not found.")
            account = ""

If you do want the line on which the username is located, you probably want something like this:

with open("accounts.txt", "r") as account_file:
    account = str(input("Enter a username: ") + " ")
    for line in account_file:
        if account in line:
            print("Found username")
            break
Matt
  • 699
  • 5
  • 15
  • Thanks, but if I enter a wrong username it won't prompt me again... – marksmansnakeeyes Aug 24 '20 at 23:11
  • The second code snippet is not wrapped in a loop and does indeed not loop when a wrong username is entered. I tested the first snippet and it does loop for me, but maybe my test version `accounts.txt` looks different? – Matt Aug 24 '20 at 23:46
  • Crap, My bad - I didn't see the first snippet but I have tested it and it worked like a charm! Thanks a million! – marksmansnakeeyes Aug 25 '20 at 15:31