Python Forum
Problem with readlines() and comparisons
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem with readlines() and comparisons
#1
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
Reply
#2
Try print (f"{repr(gefragt)} ungleich {repr(test)}") perhaps?
Reply
#3
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")
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Solved] Using readlines to read data file and sum columns Laplace12 4 3,535 Jun-16-2021, 12:46 PM
Last Post: Laplace12
  Comparisons with functions menator01 1 1,824 Jun-07-2020, 09:28 AM
Last Post: Gribouillis
  [Python3] Trailing newline in readlines. LWFlouisa 4 4,832 Mar-10-2020, 09:57 AM
Last Post: perfringo
  Problem with readlines() assignment Sunioj 5 4,755 Oct-27-2019, 06:20 AM
Last Post: perfringo
  List Comparisons and Deleting Valuebles KaleBosRatjes 4 3,703 May-13-2018, 02:14 PM
Last Post: volcano63
  readline() and readlines() rpaskudniak 9 30,072 Nov-21-2017, 07:39 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020