How do i check if two strings are on the same line in a file?

529 views python

I have a program where I ask the user their username and password, and it checks a file to see if they have the correct username and password. Each username and password is stored on its own line.

this is what I have

if username and password in open("logininfo").read():
    print("logged in succesfully")
    print("Incorrect username or password")

the problem i'm having with this is that any username can be used with any password since it check the whole file. Is there any way to check if they're on the same line in the file?

answered question

You'll simply have to read the file a line at a time, check the value, and break out of the loop when you find a match. (Python code left as an exercise to the reader.)

I recommend making a Username => Password dict. Check if the username given by the user is in the dict. If it is, check if the password matches the dict value.

2 Answers


You can easily make this function checking the file line by line

def check_password(username, password, lines):
     for line in lines:
         if username and password in line:
             return True
     return False

And you can use this function this way:

check_password(username, password, open(file_name).readlines())

posted this

Iterate over open('logininfo').readlines() and check whether the username is in a line AND the password is in a line.

In if username and password in open("logininfo"), it checks whether string username is not empty or None, which is not intended, so you need to check both the username and the password separately.


posted this

Have an answer?


Please login first before posting an answer.