Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if EXACT string is in file. Python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}')

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading