TheCosmicSquid
TheCosmicSquid

Reputation: 9

IF Statement being ignored when reading/writing from external txt.file

Beginner Programmer here, I am trying to make a program that would act as a way to register and check to see if the username imputed was already taken. My code doesn't produce any errors but the IF statement is always ignored and never produces the error message if a Username is taken.

username = input("Username: ")
def register():
    with open("Usernames.txt", "r+") as f:
        f.write("\n")
        for line in f:
            if line == username :
                print("Error")
            else:
                f.write(username)

register()

Upvotes: 1

Views: 54

Answers (4)

Razrab.ytka
Razrab.ytka

Reputation: 101

username = input("Username: ")


def register():
    with open("Usernames.txt", "r+") as f:
        for line in f.read().splitlines():  # We must read the file first and then split it into lines
            # Also for debug I advise you to look at the state of the program, for example like this
            # print(line)
            if line.strip() == username:  # strip to ignore spaces and other "empty" characters
                print("Error")
                return  # Stop if error
        f.write('\n'+username)


register()

I would be glad if I helped) Tell me if something is not clear.

Upvotes: 0

Henrique Branco
Henrique Branco

Reputation: 1940

Your f object in python corresponds to your file. For reading the lines from it you can use the .read().splitlines() methods, just like below:

for line in f.read().splitlines():
    if line == username :
        print("Error")
    else:
        f.write(username)

Upvotes: 0

Sayse
Sayse

Reputation: 43320

Mixing reading and writing will never work here, if the last item in your list is the existing username then you'd have rewritten it n times before finding out it already exists.

Instead you should just read the names into a list and then just check with in

if username in username_list:
    print("Error")
else:
    write_to_file(username)
    username_list.append(username)

Upvotes: 2

chepner
chepner

Reputation: 531918

input strips the newline from input it reads; a file iterator does not.

username = input("Username: ")
def register():
    with open("Usernames.txt", "r+") as f:
        f.write("\n")
        for line in f:
            line = line.rstrip('\n')
            if line == username :
                print("Error")
            else:
                f.write(username)

Upvotes: 2

Related Questions