python - 无法将输入变量与文件中的变量进行比较

标签 python python-3.x file validation

我正在为我的项目制作一个登录系统,我将用户名和密码存储在一个文本文件中,用户名在第一列,密码在第二列,然后用新行分隔每个登录名/密码并使用 : 作为用户名/密码之间的屏障。

输入正确的用户名和密码后,我总是得到不正确的登录信息,但是如果我只将用户名与文件进行比较,它就可以正常工作。即使我直接从文件中打印密码和用户名,然后将其打印在我输入的用户名/密码旁边,它仍然完全相同,但仍然说登录不正确!

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 or None, whitespace characters are removed. If given and not None, 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/

相关文章:

python - 为什么 json 文件会有这样的行为?

python - python 3中类 'bytes'的不同表示

python - 扁平字典和嵌套字典之间的速度性能差异

php - 使上传的文件在多个服务器之间保持同步 - PHP Linux

java - Undefined Name "Y",以及奇怪的输出问题

python - for循环中的if-else在python中不起作用

python - 在 seaborn 中绘制带阴影的堆积条形图

python - 如何在不使用 eval 的情况下替换字典值中的字符串?

python - 当我增加图表大小时,我的 2D Perlin 噪声发生器(相同种子)生成不同的图表

python - 如何在 python 中使用文本文件中的列表?