Detecting Duplicates for Registration and Login system in python

Viewed 166

I am currently creating a login system in python. The problem I am facing is I do not know how to detect if the username is taken based on a text file.

I have tried using while loops and for loops, but nothing worked. My only guess is that I have to use lists in this scenario, but I do not know how to implement it.

Any help would be greatly appreciated.

Below is the code I currently have

username = input("Please enter a username: ") 
password = input("Now please enter a password: ") 

customer_information = open("login.txt","a") 
customer_information.write(username) 
customer_information.write(" ") 
customer_information.write(password) 
customer_information.write("\n") 
customer_information.close() 
print("User was successfully registered") 
customer_login() #This command will direct the guests to the login interface
1 Answers

This logic will tell you if the username is taken or not :

username = input("Please enter a username: ") 
password = input("Now please enter a password: ") 

## ------------ check if exists


data  = open("login.txt","r")  # open file 
all_data = data.read() # read all data

accounts = all_data.split("\n") # save individual account details as list elements

account = accounts.pop() # to remove last empty data

usernames = [i.split(" ")[0] for i in accounts] # save usernames in separate list

passwords = [i.split(" ")[1] for i in accounts] # save passwords in separate list

# check for username

if username in usernames:
    print("username is taken")
else:
    print("username is not taken")


customer_information = open("login.txt","a") 
customer_information.write(username) 
customer_information.write(" ") 
customer_information.write(password) 
customer_information.write("\n") 
customer_information.close() 
Related