Check if EXACT string is in file. Python

Question:

Programme that checks if password is in file. File is from a different programme that generates a password. The problem is that I want to check if the exact password is in the file not parts of the password. Passwords are each on newlines.

For example, when password = ‘CrGQlkGiYJ95’ : If user enters ‘CrGQ’ or ‘J95’ or ‘k’ : the output is true. I want it to output True for only the exact password.

I tried ‘==’ instead of ‘in’ but it outputs False even if password is in file. I also tried .readline() and .readlines() instead of .read(). But both output false for any input.

FILENAME = 'passwords.txt'
password = input('Enter your own password: ').replace(' ', '')


def check():
    with open(FILENAME, 'r') as myfile:
        content = myfile.read()
        return password in content


ans = check()
if ans:
    print(f'Password is recorded - {ans}')
else:
    print(f'Password is not recorded - {ans}')
Asked By: user19191583

||

Answers:

One option assuming you have one password per line:

def check():
    with open(FILENAME, 'r') as myfile:
        return any(password == x.strip() for x in myfile.readlines())

Using a generator enables to stop immediately if there is a match.

If you need to repeat this often, the best would be to build a set of the passwords:

with open(FILENAME, 'r') as myfile:
    passwords = set(map(str.strip, myfile.readlines()))

# then every time you need to check
password in passwords
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.