我正在为我的项目制作一个登录系统,我将用户名和密码存储在一个文本文件中,用户名在第一列,密码在第二列,然后用新行分隔每个登录名/密码并使用 :
作为用户名/密码之间的屏障。
输入正确的用户名和密码后,我总是得到不正确的登录信息,但是如果我只将用户名与文件进行比较,它就可以正常工作。即使我直接从文件中打印密码和用户名,然后将其打印在我输入的用户名/密码旁边,它仍然完全相同,但仍然说登录不正确!
def login():
file=open("user.txt","r")
user=input("enter usename")
password=input("enter password")
Check=False
for line in file:
correct=line.split(":")
if user==correct[0] and password==correct[1]:
Check=True
break
if Check==True:
print("succesffuly logged in")
file.close()
mainMenu()
else:
print("incorrect log in")
file.close()
login()
最佳答案
我怀疑您在每个用户/密码字符串的末尾都有一个 \n
。我怀疑 line
读入后看起来像 user:pass\n
。使用 line.strip().split(':')
来删除导致 password==correct[1]
失败的换行符。
替换:
for line in file:
correct=line.split(":")
与:
for line in file:
correct=line.strip().split(":")
为什么,请参阅 https://docs.python.org/2/library/string.html#string.strip
string.strip(s[, chars])
Return a copy of the string with leading and trailing characters removed. If
chars
is omitted orNone
, whitespace characters are removed. If given and notNone
,chars
must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.
关于python - 无法将输入变量与文件中的变量进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49538705/