-2

So I have a login system in python that gets the accounts from a list

username = raw_input("Username: ")
password = raw_input("Password: ")

login = open("login.txt", "r")

for line in login:
    if line.split(":")[0] == username and line.split(":")[1] == password:
        print("It Works!")
    else:
        print("Failed")

But, it only gets the username and password from line 1 it wont go any higher. So how can I make this work? Format the accounts go in:

admin:password
nimda:drowssap
  • This is not an answer but see https://stackoverflow.com/q/9202224/2750819 and consider storing a hash of your password if you are using this for more than yourself. – Kent Shikama May 23 '18 at 17:03
  • Is there more than one line in your login.txt file? You don't have code here that adds the user-input username and password to login.txt. Also, I second @kshikama 's comment - it's good practice to hash passwords because you never know what might become of your script. – jshrimp29 May 23 '18 at 17:03
  • I would look into the line terminators in login.txt – Andrew Che May 23 '18 at 17:05
  • 1
    Your second test will always fail, as there is a `\n` at the end of `line.split(":")[1]`. – Thierry Lathuille May 23 '18 at 17:06
  • jshrimp its a text file you manually add it. So of course there is no input. Also the login.txt file is at the bottom of my post – Goten Black May 23 '18 at 17:06
  • @GotenBlack I see what you're trying to do now, but I often add lines to a text file for logging purposes, so it's not "of course". – jshrimp29 May 23 '18 at 17:10
  • Sorry about that – Goten Black May 23 '18 at 17:11
  • No worries, but it’s good to keep in mind that people have different experiences and perspectives. – jshrimp29 May 23 '18 at 17:15
  • Why exactly did I get -1 Because it doesnt meet any of the reasons for it – Goten Black May 23 '18 at 17:52

1 Answers1

0

Unfortunately I don't have Python2 to work this out with (I'm using v3.6, but I think everything below is backward-compatible to v2), but it seems the issue you're having is that login is a TextIOWrapper object and looping over it can give unexpected results. I suggest using the readlines() function on login (which creates a list) and looping over that instead. You'll also need the .strip() for each line call, as alluded to by @AndrewChe in the comments.

# I added the 'with' clause so that the file is opened fresh each run
# (for debugging - the file cursor is iterated each time a line is read)
with open("login.txt", "r") as login:
    lines = login.readlines()

for line in lines:
    if line.strip().split(":")[0] == username and line.strip().split(":")[1] == password:
        print("It Works!")
    else:
        print("Failed")
jshrimp29
  • 588
  • 6
  • 8