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

标签 python list loops

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

关于python - 遍历文本文件以在 Python 中查找用户名和密码匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32250311/

相关文章:

Python从元组列表中生成字典列表

python - 通过索引中的部分字符串匹配选择行

带有 argparse 参数表单列表的 Python 命令行参数不起作用

java - 为什么 30 秒的声音在我的 LibGDX 项目中只播放 4 秒?

java - 复合正弦近似

python - 从整数中删除最后一位并在 python 中放入零

java - (Java) 尝试对 if 语句中的打印项目进行编号

python - 使用 Python 将索引设置为 csv 文件中重复行值的组

php - 循环中的 SQL 更新(mysql、PHP)

python - 使用 brew 安装 Pyqt4