0

I am making a login script for python and it will create passwords and write them to a text file like (username:password). But I want to add a login script that will check to see if the username and password is in the text file.

def reg():
    print('Creating new text file') 
    name = input('Username: ')
    passwrd = input('Password: ')
    with open("users.txt", "r+") as f:
     old = f.read()
     f.seek(0)
     f.write(name + ":" + passwrd + "\n" + old)
    f.close()
def login():
    user = input("username: ")
    passwrd = input("password: ")

    with open('users.txt') as f:
       credentials = [x.strip().split(':') for x in f.readlines()]

    for user,passwrd in credentials:
    (This is where i want to add the code)

reg()
login()

I think it would be something like.

for user,passwrd in credentials:
    print("found")
else:
    print("not found")
4
  • 1
    That's nice. Oh did you have a question? Commented Nov 4, 2015 at 20:23
  • yes i want to add a piece of code that checks to see if the variables user and passwrd are in the file and if they are print "correct" or "incorrect" Commented Nov 4, 2015 at 20:25
  • 2
    change for user,passwrd to if [user,passwrd] if you want to check whether the inputs are in credentials list Commented Nov 4, 2015 at 20:27
  • Yes it's working now thank you verry helpfull Commented Nov 4, 2015 at 20:29

2 Answers 2

1

If you make credentials a dict, then you can do:

if user in credentials and credentials[user] == password:
   //success
else:
   //failure

This should work for making credentials be a dict

with open('users.txt') as f:
   credentials = dict([x.strip().split(':') for x in f.readlines()])
Sign up to request clarification or add additional context in comments.

Comments

0

You just check to see if they match. Note that you need to make the variable names different:

for user2,passwrd2 in credentials:
    if (user == user2 and passwrd == passwrd2):
       print ("Passed")

1 Comment

you might want to break/return if there is a match, since I doubt there will another line with the same combination

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.