VenomSnake
VenomSnake

Reputation: 37

How to associate a name to a password in Python txt file?

I have a txt file that have this data: Randy Orton|[email protected]|rko2000| Undertaker|[email protected]|deadman21| Triple H|[email protected]|HHH3|

I want to login a user with your password, but when I type a user name any password in the file allow the user to login. How can I fix this?

Example: I type "Undertaker" as user name. But in the password if I type "HHH3" ("Triple H's" password) I can login. But I want to allow only a user with his correct pass.

print("Consultar Gastos")

   while True:

       file = open("Moradores.txt", "a+")
       file1 = open("Moradores.txt", "r", encoding="utf-8")

       lerFile = file1.readlines()

       mLogin = input("Login: ")

       if mLogin not in lerFile:
           while True:
               print("Name not registered, try again")
               mLogin = input("Login: ")
               if mLogin in lerFile:
                   break

       mPass = input("Password: ")

       if mPass not in lerFile:
           while True:
               print("Wrong Password, try again")
               mPass = input("Password: ")
               if mPass in lerFile:
                   break

Upvotes: 0

Views: 53

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195428

The problem is, you need to parse the file (in this case Moradores.txt) for usernames and passwords and store this data in some data structure (in my example in dict):

# parse the users file for usernames and passwords:

users = {} # <-- we will store the users in this dictionary

with open("Moradores.txt", "r", encoding="utf-8") as f_in:
    for line in f_in:
        line = line.strip()
        if not line:
            continue
        user, email, password, _ = line.split('|')
        users[user] = (password, email)

print("Consultar Gastos")

mLogin = input("Login: ")

while True:
   print("O nome não está cadastrado, tente novamente")
   mLogin = input("Login: ")
   if mLogin in users:  # <-- change
       break

mSenha = input("Senha: ")

while True:
   print("Senha incorreta, tente novamente")
   mSenha = input("Senha: ")
   if mSenha == users[mLogin][0]:   # <-- change
       break

Note: You can print(users) to see, how the dictionary looks like.

Upvotes: 2

Related Questions