简体   繁体   中英

How do I prevent duplication in my text file when asking for registration from customer in python

My codes looks like this

def registers():
    print("\n-------------Register-------------")
    new_acc = open("register_file.txt", "a")
    new_acc_read = open("register_file.txt", "r")
    new_uname = input("Enter new username: ")
    username = []
    for line in new_acc_read:
        user = line.split()
        username.append(user[0])
        print(username)
    if new_uname in username:
        print("Username already exists.")
        new_uname = input("Enter new username: ")
    new_acc.write(new_uname)
    new_pass = input("Enter new password: ")
    if len(new_pass) < 8:
        print("Make sure password is at least 8 characters")
        new_pass = input("Enter new password: ")
    elif re.search("[0-9]", new_pass) is None:
        print("Make sure password has a number in it")
        new_pass = input("Enter new password: ")
    elif re.search("[a-z, A-Z]", new_pass) is None:
        print("Make sure password has letter in it")
        new_pass = input("Enter new password: ")
    print("Register successful! Proceed to login.")
    new_acc.write(new_uname + " " + new_pass)
    new_acc.write("\n")

I try this to prevent duplication of same usernames but everytime I rerun or when I login to an account that does not exist and return to the registers page I am able to use the same username and in my text file it turns out to be duplicated

wewewewe wewe12345
wewewewewewe wewewe12345
wewewewe wewe12345

This is the output

-------------Register-------------
Enter new username: wewe
['wewewewe']
['wewewewe', 'wewewewewewe']
['wewewewe', 'wewewewewewe', 'wewewewe']
Enter new password: wewe12345

You can refer to this simple program I made:

def register():
    x=input("Enter username: ")
    y=input("Enter password: ")
    found=False
    with open('login.txt','r+') as file:
        file1=file.readlines()
        for line in file1:
            a,b=line.strip('\n').split()
            if a==x:
                found=True
                break
        if found:
            print("Username already exist.")
            register()
        else:
            file.write(x+' '+y+'\n')
register()

Let's run the program.

Before execution, the text file is empty After executing the file:

Enter username: a
Enter password: b

Text file now:

a b

Sample execution number 2:

Enter username: a
Enter password: b
Username already exist.
Enter username: c
Enter password: d

Text file now:

a b
c d

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