简体   繁体   English

Python只读取CSV文件的第一行

[英]Python only reading the first line of CSV file

I'm sure this is simple, but it's driving me nuts.我相信这很简单,但它让我发疯。 Code only reads the first line of the CSV file.代码仅读取 CSV 文件的第一行。 If I enter the name at the top of the CSV it asks for the password.如果我在 CSV 顶部输入名称,它会要求输入密码。 If I enter any of the others in the list it goes to 'You are not currently registered'.如果我输入列表中的任何其他人,它会转到“您当前未注册”。 I can't figure out why?我想不通为什么?

with open('members.csv', 'r') as mem_login:
    login_reader = csv.reader(mem_login)
    for row in login_reader:
        if member in row:
            password = input('Please enter password...  ').lower()
            if password in row:
                print('Welcome ' + member.capitalize() + ', login successful!')
                sys.exit()
        else:
            reg_now = input('You are not currently registered. Would you like to sign-up now? Y or N   ').lower()

Your else case is attached to if member in row: , so if the first row doesn't contain the member , you immediately assume they're unregistered.您的else案例附加到if member in row: ,因此如果第一row不包含member ,您会立即假定它们未注册。 Dedent it a line to attach it to the for loop, so the else block only fires if the for loop runs to completion without break ing: Dedent 一行以将其附加到for循环,因此else块仅在for循环运行完成而没有break才会触发:

# newline='' is mandatory for csv module to handle dialect's newline conventions
# mode defaults to 'r', so you don't need to use it
with open('members.csv', newline='') as mem_login:
    # Unpack to username and userpass, and test individually, 
    # so user names are not their own passwords
    for username, userpass in csv.reader(mem_login): # One-lined creation of reader since it's only needed for loop
        if member == username:
            password = input('Please enter password...  ').lower()
            if password == userpass:
                print('Welcome ' + member.capitalize() + ', login successful!')
                break  # break bypasses the for's else block
    else:
        # Only runs if break not executed
        reg_now = input('You are not currently registered. Would you like to sign-up now? Y or N   ').lower()

I made few other small fixes/improvements (all commented), but the big change is the dedent of the else block to attach it to the for loop, not the if .我做了一些其他小的修复/改进(所有评论),但最大的变化是else块的 dedent 将它附加到for循环,而不是if

Note: Even with my changes, this has serious flaws (caseless passwords, passwords in plaintext), so never use it for real user authentication.注意:即使经过我的更改,这也存在严重缺陷(无壳密码、明文密码),因此切勿将其用于真实用户身份验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM