如何比较从python到csv的行?

时间:2017-10-21 20:19:08

标签: python file csv

我试图创建一个允许用户使用包含列出信息的现有csv文件登录的程序。如何让程序读取文件以找到存储在其中的用户名和密码?下面是我试图运行的代码:

   login = input("To sign in type 1. To register a new account type 2: ")
if login == "1":
    log_username = True
    while log_username == True:
        user = input("Username: ")
        user_password = input("Password: ")
        saved_users = open(user+".csv","r")
        for line1 in saved_users:
            line1.split(",")
            for line2 in saved_users:
                line2.split(",")
                if user == saved_users:
                    if user_password == saved_users:
                            print("Login successful...")
                    else:
                        print("Incorrect password")
                        log_username == False
                else:
                    print("Incorrect username, please try again.")
                    log_username == False

Example of csv

1 个答案:

答案 0 :(得分:0)

这应该适合你(注意这意味着没有重复的用户名):

import csv
import re

user = input("Username: ")
user_password = input("Password: ")

with open('test.csv', 'r') as saved_users:
    reader = csv.reader(saved_users)
    for line in list(reader)[1:]: # I start at 1 to skip the column labels
        line = [re.sub('[\[\]\']', '', item) for item in line] # This cleans up the brackets and quotes from the csv file
        if line[0] == user and line[1] == user_password:
            print("Login successful...")
            break
    else:
        print("Incorrect password")