Search code examples
pythonuser-input

How to compare information from a file in python


So I have a file and I want to compare it with my user's input so that the file's information may equal what the user has inputted. In the reg_login.txt it holds information.

 Username = Emmanuel, Password = emman
 Username = Emmanuel, Password = em

I want the code to compare the user's input and the reg_login.txt and make sure that what it says in the text file is equal with the program. If it doesn't equal then ask the user to input again and again until the reg_login.txt is equal with the user's input

When I write the code

username1 = input("What is your username?: ")

password2 = input("What is your password!")

reg = open("reg_login.txt")

if username1 = "Username =" = open("reg_login.txt")

if password2 = "Password =" = open("reg_login.txt")

I expected the program to compare the strings and variables.


Solution

  • compare the strings and variables

    open() alone does not read the file. You will need to iterate over the lines.

    For example,

    match = False
    while not match:
      user = input("What is your username?: ")
      password = input("What is your password!")
    
      with open("reg_login.txt") as f:
        for line in f:
          if line.startswith(f'Username = {user},') and line.rstrip().endswith(f'Password = {password}'):
            print('Matching user!')
            match = True
            break
    
    print(f'Hello {user}.')
    

    Keep in mind - passwords should never be stored or entered as easily readable plaintext values.