Python 代码无法识别csv文件中特定单元格中的字符串
我正在创建一个登录和菜单程序,我有一个CSV文件,里面有我发明的一些用户的登录和密码。当我运行程序时,它没有任何错误,但是当我引入正确的用户名和密码时,它不能正常工作 我的代码在打印“已授予访问权限”时打印“未授予访问权限” 这是我在控制台中打印CSV时的外观:Python 代码无法识别csv文件中特定单元格中的字符串,python,csv,Python,Csv,我正在创建一个登录和菜单程序,我有一个CSV文件,里面有我发明的一些用户的登录和密码。当我运行程序时,它没有任何错误,但是当我引入正确的用户名和密码时,它不能正常工作 我的代码在打印“已授予访问权限”时打印“未授予访问权限” 这是我在控制台中打印CSV时的外观: [['Username' 'Password' 'Access Level'] ['booker12' '12se74' '1'] ['grey07' '04ap67' '1'] ['johnson81' '30no86' '1'] [
[['Username' 'Password' 'Access Level'] ['booker12' '12se74' '1'] ['grey07' '04ap67' '1'] ['johnson81' '30no86' '1'] ['jenkins46' '14ju73' '1'] ['smith79' '09ja61' '1'] ['ccastrej' 'superuser03' '3'] ['ssofia' 'semigod1' '2'] ['isabella' 'payasian' '2'] ['pablitohesk' 'soccer13' '2'] ['teacher' 'igradethis100' '3'] ['pedrocorte' 'asturiano' '1'] ['andrea' 'jesusito' '1']]
以下是我现在掌握的代码:
import sys
import csv
import numpy as np
def Main():
login()
def login():
with open('MatrixAccess.csv') as csvfile: #I import the csv file
reader = csv.reader(csvfile, delimiter = ';') #I read through it
x = list(reader) # I convert the csv into an array to loop through it easier with the numpy library
print(np.matrix(x)) #I print it to check if I imported it correctly
print("Username: ")
str1 = input()
print("Password: ")
str2 = input()
for i in [2]:
for j in [i]: #I have to convert the ints to lists so I can iterate through the list
if(str1 == x[i][j] and str2 == x[i][j+1]):
print("Access granted")
else:
print("Access not granted")
def menu():
print("************MAIN MENU**************")
你的循环完全错了<[2]中的code>for i意味着在该1元素列表上循环,这与只写
i=2
而不写任何循环没有什么不同
您应该循环浏览包含读取文件结果的列表x
for row in x[1:]:
if str1 == row[0] and str2 == row[1]:
print("Access granted")
break
else:
print("Access not granted")
x[1://code>跳过标题行。请注意,else:
块位于for
循环中,而不是if
语句中;只有在到达循环末尾而不中断时,此操作才会运行。如果您将它放在If
语句中,它将为文件中不匹配的每一行报告一个错误;请参见这不是CSV文件。一切都是这样的吗?对于[2]
中的i和对于[i]
中的j减少到i,j=2,2
,不需要循环。