user12739323
user12739323

Reputation:

Correct loop to read data, compare data and write data from txt file

Could someone please lend some advice with the following problem I am having.

I need to ask a user to input a username and then password. I then need to compare the username and password to an external txt file which has the correct username and passwords stored. For the programming side, I need to create a loop until the correct username is entered and then when the correct password is entered. I need to also display if the username is correct but not the password. I'm just struggling with choosing which loop to use and how to structure this code.

The text file contains:

admin, admin1

admin is the username admin1 is the password

The code I have so far is below which works fine but it doesn't contain the correct loop.

with open('user.txt')as username:
  contents = username.read()
  user = input("Please enter your username:")
  if user in contents:
          print("Username correct")

  else:
        print ("Username incorrect. Please enter a valid username") 

Upvotes: 1

Views: 58

Answers (1)

sim
sim

Reputation: 1257

Leaving aside the approach for verifying a password, you could do the following. First you collect the usernames and passwords into a dictionary users (keys: usernames, values: password). Then you use a while loop that checks your users' input against this dictionaries keys (using not in users) until an input matches.

users = {}  # dictionary that maps usernames to passwords
with open('user.txt', 'rt') as username:
    for line in username:
        uname, password = line.split(",")
        users[uname.strip()] = password.strip()  # strip removes leading/trailing whitespaces

uinput = input("Please enter your username:")
while uinput not in users:
    print("Username incorrect. Please enter a valid username")
    uinput = input("Please enter your username:")

# do stuff with password etc.

Upvotes: 2

Related Questions