我正在做的该程序的一部分需要用户输入(用户名),并检查它是否已存在于文本文件中。如果已经存在,则打印(“用户名已经存在”。) 但是现在,不管输入是否已存在于文本文件中,程序都会继续将输入添加到文本文件中。 有人知道如何解决吗?(这是btw的一部分)
def passcheck():
user=name_ent2.get()
pass1 = pass_ent2.get()
confirm = retype_ent.get()
names = open("nlist.txt","a+")
if user in names:
print("username already exists.")
if user not in names:
names.write(user)
names.write('\n')
names.close()
When you test membership with
user in names
, Python iterates on the lines of the file and comparesuser
with each of the lines.The problem here is that the newline
\n
in included in the line, so your name won't match.因此,在比较之前,您必须删除此换行符的行,例如: