简体   繁体   中英

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. If I enter the name at the top of the CSV it asks for the password. 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. 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:

# 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 .

Note: Even with my changes, this has serious flaws (caseless passwords, passwords in plaintext), so never use it for real user authentication.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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