Why is python not recognizing when a string is in a file

Viewed 55

I am making a pretend login system as a project. When the in_file variable is in the file I want it to print you are logged in. However, it doesn't do this since it doesn't think that the in_file variable is in the file. How do I fix this?

sample of the file

username/password

Matthew/06112004

James/Nemo20044!

account = input('do you want to sign up or login ? ')
file = open('login.txt', 'a+')

def log_in(filename):
    logging_in = True
    while logging_in:
        username = input('Username: ')
        password = input('Password: ')
        in_file = f'{username}/{password}'
        if in_file in filename.read():
            print('you are logged in')
            logging_in = False
        if in_file not in filename.read():
            print('user name or password are incorrect')

if account == 'login':
    log_in(file)
1 Answers

You need to open the file with the 'r'(read) mode, the 'a' mode will only let you append to the file.

So change file = open('login.txt', 'a+') to file = open('login.txt', 'r').

Note that it is not a very good practice to open() and close() a file. Instead, use a context manager.

Related