KingJC
KingJC

Reputation: 11

How can I check if a string is in a text file? (python)

I am doing a project for school - and as part of it, I need to check if their username is already stored within a text file:

def checkUsername():
    userName = str(input("WHAT IS YOUR NAME?"))
    if userName in usernames.read():
        print("WELCOME BACK" + userName)
        print("LET\'S GET STARTED")
        return False
    else:
        usernames.write(userName)
        print("WELCOME TO THE SYSTEM!")
        return False

Despite my efforts to resolve this issue, I cannot seem to figure it out. Can anyone help?

Upvotes: 0

Views: 4394

Answers (3)

Pedro Lobito
Pedro Lobito

Reputation: 98881


i.e.:

def checkUsername(user):
    if user.strip():
        with open("myfile") as users:
            print(f"WELCOME BACK {user}\nLET'S GET STARTED") if user in users.read() else print(f"WELCOME TO THE SYSTEM!")
    else:
        print("Error: empty username")

user = input("WHAT IS YOUR NAME?")
checkUsername(user)

Upvotes: 1

Andrew F
Andrew F

Reputation: 2950

One issue with this function is that usernames is not defined, and the other is that both ends of the if block will return False.

One way you could solve these would be

def checkUsername(usernames_file):
    fp = open(usernames_file, 'r')  # the default mode is 'r', but it's explicit here
    usernames = fp.read()

    userName = str(input("WHAT IS YOUR NAME?"))
    if userName in usernames:
        print("WELCOME BACK" + userName)
        print("LET\'S GET STARTED")
        fp.close()
        return True  # note, not False
    else:
        fp.write(userName)
        print("WELCOME TO THE SYSTEM!")
        fp.close()
        return False

That snippet above is different in a few ways, but it also ignores two likely errors you might also be facing: case sensitivity in inputs (the input(...) line could be whatever the user wants), and line separation in usernames_file. Hopefully this pushes you in the right direction though.

Upvotes: 1

yuvgin
yuvgin

Reputation: 1362

What you are missing is first opening the file for reading:

def checkUsername():
    userName = str(input("WHAT IS YOUR NAME?"))
    with open("usernames.txt", 'r') as usernames:    
        if userName in usernames.read():
            print("WELCOME BACK" + userName)
            print("LET\'S GET STARTED")
            return False
        else:
            usernames.write(userName)
            print("WELCOME TO THE SYSTEM!")
            return False

with open opens the file at the specified path (change usernames.txt to the full path of the file) and 'r' signifies that the file is to be opened with reading permissions. This is usually advantageous to using python's open() method, which requires you close() the file when you are finished reading it.

Side note: notice you have returned False under both conditions of your function.

Upvotes: 2

Related Questions