Home > OS >  Check if EXACT string is in file. Python
Check if EXACT string is in file. Python

Time:11-07

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

CodePudding user response:

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
  • Related