sceneturkey
sceneturkey

Reputation: 21

(Python) How to test if a string is contained in a file

I'm trying to create a username database and the code all runs how I want except for when I try to test if the file contains the entered text. For some reason it just runs past the elif statement and hits the else statement if it already exists in the text.

Here is the full code:

class username:
    def add():
        while(True):
            file = open("usernames.txt", 'r+')
            names = list(file.read())
            entered = str(input("Username: "))
            if len(entered) == 0:
                print("Please enter a valid username\n")
                continue
            elif not(entered.isalpha):
                print("Please enter a valid username\n")
                continue
            elif entered in file.read():
                print("That name is already in use.",
                      "\nPlease enter a different username. \n")
                continue
            elif len(entered) < 4 or len(entered) > 12:
                print("Please enter a username with 4-12 characters.\n")
                continue
            else:
                print(entered)
                file.close()
                add = open("usernames.txt", 'a+')
                plusnewline = entered + "\n"
                add.write(plusnewline)
                add.close()
                break

    def list():
        file = open("usernames.txt","r+")
        names = file.read()
        print(names)
        file.close()

username.add()
username.list()

edit: Answered by Shadow:

Changed:

names = list(file.read())

to:

names = file.read()

and changed:

elif entered in file.read():

to:

elif entered in names:

Upvotes: 2

Views: 54

Answers (1)

Shadow
Shadow

Reputation: 9427

You can only call file.read once - after that it's already read.

Either use file.seek(0) to go back to the start of the file (which will allow you to read it again), or cache the contents in a variable so that you can reuse it (that is, refer to your names variable)

Upvotes: 2

Related Questions