在Python中迭代文本文件以查找用户名和密码匹配项

在Python中迭代文本文件以查找用户名和密码匹配项,python,list,loops,Python,List,Loops,for循环的结构看起来是错误的。出于某种原因,它没有正确地跳转到语句的“else”部分。我将在控制台中尝试这一点,以简化一些事情,看看我是否运气好: def verifylogin(): fin=open("moosebook.txt","r") data=fin.readlines() for line in data: fields=line.split() fields=[i.rstrip("','") for i in fields] #strips the named

for循环的结构看起来是错误的。出于某种原因,它没有正确地跳转到语句的“else”部分。我将在控制台中尝试这一点,以简化一些事情,看看我是否运气好:

def verifylogin():
fin=open("moosebook.txt","r")
data=fin.readlines()
for line in data:
    fields=line.split()
    fields=[i.rstrip("','") for i in fields] #strips the named character from END of field
    fields=[i.replace("'",'') for i in fields]#when reading the list, you want to remoe the ',' so it isn't part of the username or password
    fields=[i.replace("(",'') for i in fields] #simiarly, remove the bracket and replace it
    line=line.rstrip()
    print(fields)

    access_permitted = False
    for counter in range(0,len(fields)):
        if textlogin.get()==fields[counter] and textpassword.get()==fields[counter+1]:
            access_permitted=True
            if access_permitted:
                    welcome=Label(myGui,text="Access Granted. Loading Profile ....")
                    welcome.pack()

        else:
                    denied=Label(myGui,text="Access Denied")
                    denied.pack()

按照循环的构造方式,文件中与用户名/密码不匹配的每一行都会收到“拒绝”消息,而与用户名/密码不匹配的每一行都会收到“接受”消息。如果您只想显示一条消息,那么等待循环结束后再创建一条消息

access_permitted = False
for i,s in enumerate(fields):
    if textlogin.get()==fields[i] and textpassword.get()==fields[i+1]:
        access_permitted = True

if access_permitted:
    welcome=Label(myGui,text="Access Granted. Loading Profile ....")
    welcome.pack()
else:
    denied=Label(myGui,text="Access Denied")
    denied.pack()
    line=fin.readline()

我不能肯定,但似乎循环中也会出现
索引器:列表索引超出范围的
错误,因为
字段[I+1]
在最后一次迭代中超过了列表的末尾。我猜
字段
是一个包含用户名+密码元组的列表,在这种情况下,您应该尝试:

for username, password in fields:
    if textlogin.get()==username and textpassword.get()==password:
        access_permitted = True
如果
字段
不是用户名密码元组列表,您可能需要尝试其他方法


如果
字段中的每个项目都包含用户名和密码以及其他项目,请尝试:

for row in fields:
    if textlogin.get()==row[0] and textpassword.get()==row[1]:
        access_permitted = True

你能展示一下
字段的样子吗?你能描述一下结果吗?你确定textlogin.get()和textpassword.get()有效吗?是的,textlogin和textpassword肯定有效。我也尝试过这样做:结果:在输入“字段[0]和字段[1]”作为用户名和密码时,它会出现“已授予访问权限”…然后有几个访问被拒绝。当我输入下一组用户名和密码时,它会做类似的事情,只是开始时有几次访问被拒绝,然后是一次访问被授予。换言之,这是一种工作,但不完全…我要去吃点午饭,然后看看是否有效-天哪,谢谢你的快速反应!虽然我相信我已经确定了主要问题,但我不认为我建议的代码是现成的<代码>字段[i+1]
可能会出现“索引超出范围”错误。不过,我还不能提出更好的建议,因为我不知道
字段是如何创建的,也不知道它的内容是什么。我刚刚编辑添加了内容:>>['CoderBlogJ'、'ggs123'、'J'、'Bloggs'、'Male'、'Coder')]['LovelyMarvJ'、'vin123'、'J'、'Marvin'、'Male'、'Lovely')]输出:12拒绝访问(不输入任何内容)。在正确获取它时(例如,用户名和密码为CoderBlogJ和ggs123),它会说“已授予访问权限”,然后是几次访问被拒绝……你是说我的第三个代码块不起作用吗?如果不是的话,我认为我们真的需要看到一个解决方案,这样我们就可以在自己的机器上复制这个问题。