Search code examples
pythonexternal

Python - matching data from an external file (username password)


I know it's something to do with the newline tag, but why can't my program find a username/password match in my external file?

username = input("Please enter your username: ")
password = input("Please enter your password: ")
file = open("UsernamesPasswords.txt", "r")
for loop in file:
    line = file.readline()
    data = line.split(",")
    print(data)
    if username == data[0] and password == data[1]:
        print("That's a match")
    else:
        print("That's not a match!")
        break
file.close()

Solution

  • Assuming that the UsernamesPasswords.txt looks like this:

    username_1,password_1
    username_2,password_2
    username_3,password_3
    

    We can write the code:

    username_input = input("Please enter your username: ")
    password_input = input("Please enter your password: ")
    file = open("UsernamesPasswords.txt", "r")
    contents = file.read()
    file.close()
    
    for line_index, line in enumerate(contents.splitlines()):
        parts = line.strip().split(",")
    
        if len(parts) != 2:
            # Incorrect line
            continue
    
        username, password = parts
    
        if username == username_input and password == password_input:
            print(f"That's a match, at line {line_index}.")
        else:
            print(f"That's not a match, at line {line_index}.")
            break