For my class project, I have to make a simple Username Inventor and store the Usernames in a file. This is what I have done and it is working.
An additional part to the project is, if a duplicate is added to the file, that duplicate needs to be deleted and replaced with a "#". But the "#" has to be next to the original Username that was the duplicate.
Please can someone show me how to do this, as a for reference this is my code below:
print("Hello, Welcome to the Username Inventor.")
Name = input("Please tell me, What is your name? ")
print(Name+"......")
print("I like....")
print("Anyway, lets get on shall we.")
with open("Interim.txt", "a") as file:
true = True
while true == True:
choice = input("(1)Add a Pupil's Username to the file\n(2)Exit the program\n")
if choice == "1":
true = False
print("Please identify the following:")
FirstName = input("Pupil's First Name: ")
Surname = input("Pupil's Surname: ")
YearOfEntry = input("Pupil's Year of Entry: ")
print("Thank you",FirstName, Surname, "from year joining at",YearOfEntry+".")
Initial = FirstName[0]
Username = YearOfEntry+Surname+Initial
print("This Pupil's Username is",Username+".")
file.write(Username)
file.write("\n")
true = True
if choice == "2":
print("Thank you", Name+". Goodbye!")
true = False
Help will be very much appreciated, thank you.
You can use a list to check if new username is already in the list. Create a list and add the usernames to the list. Before writing username to the file, use 'if' statement to check if username is already in the list, if it is, then file.write("#\\n") otherwise file.write("username").
Replace your following two lines:
file.write(Username)
file.write("\n")
For:
username_list = [] #make empty list before your with open statement.
...
if Username not in username_list:
file.write('%s\n'%Username)
username_list.append(Username)
else:
file.write('#\n')
username_list.append("#")
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.