Python Forum

Full Version: Problem with readlines() and comparisons
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to write a program that reads the passwords from a file and compares them with a user input. The comparisons don't seem to work, though. The if-conditions are also called unequal ("ungleich") if this is not the case.

gefragt = input("Zu testendes Passwort: ")

sicher = 1

textdatei = open("passwoerter.txt","r")
passwoerter = textdatei.readlines()

for test in passwoerter:
    if test == gefragt:
        sicher = 0
        print (f"{gefragt} gleich {test}")
    else:
        print (f"{gefragt} ungleich {test}")
        
if sicher == 0:
    print("Unsicher")
else:
    print ("Sicher")
Output (input=password):
Zu testendes Passwort: password
password ungleich 123456
password ungleich password
password ungleich 12345678
password ungleich qwerty
password ungleich 123456789
Sicher
Try print (f"{repr(gefragt)} ungleich {repr(test)}") perhaps?
The splitlines() method and also the iteration over a file-object, does not strip the line ending.
In real, you compare 123456\n with password and so on. Use the method rstrip() to get rid of line endings and white space on the right side of the str.

You should also use a function instead and a context manager with a for-loop inside:

def test_password():
    gefragt = input("Zu testendes Passwort: ")
    with open("passwoerter.txt") as fd:
        for password in fd:
            if password.rstrip() == gefragt:
                return True
    return False
Using the function:
if test_password():
    print ("Sicher")
else:
    print("Unsicher")