Python - 在迭代CSV

时间:2017-10-21 10:59:59

标签: python csv

我已经获得了包含一些信息的CSV,代码将遍历CSV中的每一行,如果输入的用户名与该行中的值匹配,则允许用户登录。

但是,我不确定如何让我的程序说明他们的详细信息是否正确。 "未找到"在每次迭代后打印出来,而不是在CSV的末尾打印出来。

我怎么能这样做,以便一旦它在for循环结束时,它说没有找到细节?

感谢。

username = str(input("Enter your username: "))
password = str(input("Enter your password: "))

file = open("details.csv","r")
print('Details opened')
contents = csv.reader(file)
print('reader established')

for row in contents:
    print('begin loop')
    if username == row[4]:
        print("Username found")
        if password == row[3]:
            print("Password found")
            main()
    else:
        print("not found")

2 个答案:

答案 0 :(得分:2)

使用break,无论如何stop using print for debugging

for row in contents:
    print('begin loop')
    if username == row[4]:
        print("Username found")
        if password == row[3]:
            print("Password found")
            main()
            break
else:
    print("not found")

答案 1 :(得分:1)

简单的解决方案是添加变量is_found作为示例:

is_found = False

for row in contents:
    print('begin loop')
    if username == row[4]:
        print("Username found")
        if password == row[3]:
            print("Password found")
            main()
            is_found = True

if not is_found:
    print("not found")