【发布时间】:2017-09-09 11:48:49
【问题描述】:
如果银行详细信息(用户和相应号码)匹配,我有以下代码试图将文件内容读入列表(此位有效),然后显示接受消息。
例如如果输入用户名:customer1 和 account_number:1 >> 文件中每个客户和帐号的访问权限被授予等等。
文件详情
customer1,1
customer2,2
customer3,3
customer4,4
customer5,5
代码
def strip_split_read_from_file():
bankdetails=[]
with open("bankdetails.txt","r") as f:
for line in f:
line=line.rstrip() #r strip removes the new line character from the right side of the string
split_line=line.split(",")
for field in split_line:
bankdetails.append(field)
accessgranted=False
while accessgranted==False:
username=input("username:")
password=input("account no:")
for i in bankdetails:
if username==bankdetails[i] and password==bankdetails[i+1]:
accessgranted=True
break
else:
accessgranted=False
if accessgranted==True:
print("Access Granted")
else:
print("Sorry, wrong credentials")
错误
if username==bankdetails[i] and password==bankdetails[i+1]:
TypeError: list indices must be integers, not str
为了回答和教学/学习目的,我想要以下内容
使用现有提供的代码进行更正,并清楚地解释错误
关于以最有效的方法实现相同目标的替代方法的建议
【问题讨论】:
-
错误是for循环中的i不是数字它是bankdetails的迭代器。尝试打印(i),你会看到