如何比较从python到csv的行?
问题描述:
我试图创建一个程序,允许用户使用现有的csv文件包含列出的信息登录。如何让程序读取文件以找到存储在里面的用户名和密码?下面是代码,我试图运行:如何比较从python到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
答
这应该为你工作,然后(注意,这意味着没有重复的用户名):
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")
您应该使用csv模块,而不是试图自己分裂它。 – gommb
你能展示一个你正在使用的csv文件的设置示例吗? – gommb
@gommb ive现在附上上述问题中的示例。 –