Python Forum

Full Version: Data is in and not in the file at the same time
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone!

At the moment I'm working on a simple Regiter/Login project which uses text file to store all the data.

username=input("Please enter your username: ")
    with open("Data.txt", "r") as DataFile:
        for i,line in enumerate(DataFile):
            if username in line:
                print("Found the user in line:",i)
                data=line.split()
                password=data[1]
                print(password)
        if username not in DataFile:
            print("Username ",username," not found!")
I get no error messages, but the problem is that both if statements are correct- at the same time username is and not in the file. Any help would be appreciated.


The output:

Please enter your username: Jeff
Found the user in line: 1
123
Username Jeff not found!


DataFile:

Jeff 123
Sandra 753
Mike 482
You are checking if username is in the entire line...which it is. You should split the data first and compare it only to the first element (since the username is always first)
    for i,line in enumerate(DataFile):
        data=line.split()
        if username in data[0]:
            password = data=[1]
And for the second if clause you could use a boolean to compare between all loops.
username=input("Please enter your username: ")
found = False
with open("Data.txt", "r") as DataFile:
    for i,line in enumerate(DataFile):
        data=line.split()
        if username in data[0]:
            password = data=[1]
            found = True
            
if not found:
    print("Username {} not found!".format(username))
Or you could use a function to return found boolean
username=input("Please enter your username: ")
with open("Data.txt", "r") as DataFile:
    lines = DataFile.readlines()
    
def user_found(username, lines):
    for line in lines:
        data=line.split()
        if username in data[0]:
            return True

if not user_found(username, lines):
    print("Username ",username," not found!")