首页 > 解决方案 > Python 简单的用户名/密码和字典

问题描述

我对 Python 世界很陌生,并且认为通过我儿子的 Python 书为初学者工作会很棒。我正在将所有当前章节组合成一个交互式“从列表中选择...”,以熟悉基础知识。其中一个部分包括验证存储在代码本身中的用户名/密码,但我想我会更进一步,看看我是否可以从文件中读取。

我设法拼凑了以下内容,但它只会从密码文件的最新行中读取:

with open('password.csv', "r") as csvfile:
    reader = csv.DictReader(csvfile)
    database = [] #creates a list holder for the data
    for row in reader:
        database.append(dict(username=row["username"],
                            password=row["password"]))

authenticated = False
while not authenticated:
        username = input("Enter the username: ")
        password = input("Enter the password: ")
        for row in database:
            userFile = row["username"]
            passwordFile = row["password"]
        if (userFile) == username and (passwordFile) == password:
            authenticated = True
        if authenticated is not True:
            print("Incorrect credentials")

有更多经验的人可以指出我哪里出错了吗?这对我的水平来说太高级了,我应该做一些不同的事情吗?

标签: python-3.x

解决方案


感谢您的建议,但我自己设法解决了这个问题,这完全是因为我对 Python 缺乏经验。我的代码中的间距不正确。简单的!


推荐阅读