0

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}')
3
  • There is not enough information. How are passwords separated in the file? Commented Nov 6, 2022 at 19:03
  • 1
    In general, you need to read all passwords into a list of strings and then check using in Commented Nov 6, 2022 at 19:04
  • Newline for each password Commented Nov 6, 2022 at 19:04

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the response. That sorts my problem.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.