对于我的课程项目,我必须创建一个简单的Username Inventor并将用户名存储在一个文件中。这就是我所做的,它正在发挥作用。
项目的另一部分是,如果向文件添加了副本,则需要删除该副本并替换为“#”。但是“#”必须位于原始用户名的旁边。
请有人告诉我如何操作,作为参考,这是我的代码:
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
非常感谢帮助,谢谢。
答案 0 :(得分:0)
您可以使用列表检查列表中是否已有新用户名。创建一个列表并将用户名添加到列表中。在将username写入文件之前,使用'if'语句检查用户名是否已经在列表中,如果是,则file.write(“#\ n”),否则file.write(“username”)。
替换以下两行:
file.write(Username)
file.write("\n")
有关:
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("#")