我有以下文件 (bankdetails.txt)
customer1,1
customer2,2
customer3,3
customer4,4
customer5,5
以及以下代码旨在: 1.要求用户输入customerid和帐号(例如customer1和1),如果与文件详细信息匹配,则打印“access granted”,否则打印“denied”。
代码如下。(注意我不知道如何继续的地方?)
def read_from_file_csv_method2():
accessgranted=False
while accessgranted==False:
with open("bankdetails.txt","r") as f:
reader=csv.reader(f)
for row in reader:
for field in row:
username=input("uesrname:")
accountno=input("account no:")
if username==field and accountno==?:
accessgranted=True
break
else:
accessgranted=False
if accessgranted==True:
print("Access Granted")
else:
print("Sorry, wrong credentials")
请回答以下问题
- 使用我的原始代码更正错误。解释可以做什么来访问字段(通过索引)
- 提出使用 csv 读取器方法实现相同目标的任何更简单的方法
更新: 我知道字典是最合适的,但我想针对这个特定场景使用这些构造来解决这个问题。
例如,下面的代码有效,但仅适用于第一次迭代(customer1 和 1)...不适用于其他任何内容。
if username==row[0] and accountno==row[1]:
下面的代码中使用了上面的内容...但仍然不太有效
def read_from_file_csv_method2():
accessgranted=False
while accessgranted==False:
with open("bankdetails.txt","r") as f:
reader=csv.reader(f)
for row in reader:
username=input("uesrname:")
accountno=input("account no:")
if username==row[0] and accountno==row[1]:
accessgranted=True
break
else:
accessgranted=False
if accessgranted==True:
print("Access Granted")
else:
print("Sorry, wrong credentials")
最佳答案
你可以试试这个:
import csv
data = csv.reader(open('filename.txt'))
username=input("uesrname:")
accountno=input("account no:")
new_data = [{a:b for a, b in zip(["name", "id"], i)} for i in data]
if any(i["name"] == username and i["id"] == accountno for i in new_data):
print("Access Granted")
else:
print("Sorry, wrong credentials")
更简单的方法涉及 and 函数和 for 循环:
def check_credentials(users, username, id):
for user, the_id in users: #here, unpacking from list. user is the first value in the list that is created via iteration.
if user == username and the_id == id:
return True #return will break out of the for loop
return False #if the loop has not been broken out of at the end of the iteration, it will return False
data = csv.reader(open('filename.txt'))
username=input("uesrname:")
accountno=input("account no:")
if check_credentials(data, username, accountno):
print("Access Granted")
else:
print("Sorry, wrong credentials")
没有函数:
flag = False
for user, the_id = data: #data is the csv file.
if user == username and the_id == accountno:
flag = True
break
if flag:
print("Access Granted")
else:
print("Sorry, wrong credentials")
关于python - 在 Python 中使用 csv reader 搜索两个值的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46131588/