Skip to main content
 首页 » 编程设计

python之遍历文本文件以在 Python 中查找用户名和密码匹配项

2025年05月04日17myhome

for 循环的结构看起来不对。由于某种原因,它没有正确跳转到语句的“其他”部分。我将在控制台中尝试这个来简化一些事情,看看我是否有任何运气:

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() 

我不能肯定地说,但您似乎也可能会在循环中遇到 IndexError: list index out of range 错误,因为 fields[i +1] 在最后一次迭代中超过列表的末尾。我猜 fields 是一个包含用户名 + 密码元组的列表,在这种情况下你应该尝试:

for username, password in fields: 
    if textlogin.get()==username and textpassword.get()==password: 
        access_permitted = True 

如果 fields 不是用户名-密码元组列表,您可能需要尝试其他方法。


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

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