简体   繁体   中英

Text won't append in .txt file - Python

So I just started learning python and tried a little project that consists of a login system. I want usernames and passwords to save into.txt files but they just won't and I can't figure out the error. The issue must be happening in the register dunction that I've defined because login works just fine with the username and password that I've introduced manually.

def register():
    user = input("Registration page\nUSERNAME:")
    users = open("users.txt", "r")
    if user in users:
        print("That user already exists!")
        login()
        users.close()
    else:
        pwrds = open("pass.txt", "a")
        users = open("users.txt", "a")
        users.write("\n" + user)
        p1 = input("PASSWORD:")
        p2 = input("CONFIRM PASSWORD:")
        if p1 == p2:
            pwrds.write("\n" + p1)
            login()
            users.close()
            pwrds.close()
        else:
            print("Failed password confirmation, restarting")
            register()
            users.close()
            pwrds.close()

Thank you in advance for the help!

When you're checking the string inclusion ( user in ) in the file object ( users ), you always get False because each line is appended with the escaped new-line character '\n'.

Also, you're trying to open the file twice. There's no point for doing such of thing. You can open it passing the 'r+' parameter from the beginning.

Please note that the 'r+' method will put the initial position of the cursor at the beginning of the file, but since we're calling the read() method, then the cursor will be now set to the end of the file, allowing us to write the new user in the last position of it.

I would do this like follows:

def register():
    user = input("Registration page\nUSERNAME:")
    file = open("users.txt", "r+")
    users = file.read().splitlines() # considering you are saving the users one by one, in each line.
    if user in users:
        print("That user already exists!")
        users.close()
        login()
    else:
        pwrds = open("pass.txt", "a")
        users.write("\n" + user)
        users.close()
        p1 = input("PASSWORD:")
        p2 = input("CONFIRM PASSWORD:")
        if p1 == p2:
            pwrds.write("\n" + p1)
            pwrds.close()
            login()
        else:
            print("Failed password confirmation, restarting")
            pwrds.close()
            register()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM