问题
I am doing a Python project where I have to verify my username and password from a csv file where the first two rows and columns have the username and password as 'hi'.
Current Code:
answer = input("Do you have an account?(yes or no) ")
if answer == 'yes' :
login = False
csvfile = open("Username password.csv","r")
reader = csv.reader('Username password.csv')
username = input("Player One Username: ")
password = input("Player One Password: ")
for row in reader:
if row[0]== username and row[1] == password:
login = True
else:
login = False
if login == False:
print("Incorrect. Game Over.")
exit()
else:
print("You are now logged in!")
else:
print('Only Valid Usernames can play. Game Over.')
exit()
CSV file : https://thecompton-my.sharepoint.com/:x:/g/personal/001422_thecompton_org_uk/EbhI4A12pg1EhMezOR8tOlgBF-iOh8JTAM3x3WUOk3i9Ig?e=AJktHi
回答1:
Here is what you want
First you had wrong login logic I changed the file name for my convinience
import csv
login = False
answer = input("Do you have an account?(yes or no) ")
if answer == 'yes' :
with open('upassword.csv', 'r') as csvfile:
csv_reader = csv.reader(csvfile)
username = input("Player One Username: ")
password = input("Player One Password: ")
for row in csv_reader:
print(row[0], row[1])
print(username, password)
if row[0]== username and row[1] == password:
login = True
break
else:
login = False
break
if login == True:
print("You are now logged in!")
else:
print("Incorrect. Game Over.")
exit()
else:
print('Only Valid Usernames can play. Game Over.')
exit()
I have also some print statements to help you understand the workflow
And try to avoid opening files like this
csvfile = open("Username password.csv","r")
回答2:
I assume the .csv
file contains a list of usernames and passwords which is why you are looping through it.
Firstly, I think you have your conditionals the wrong way round. You currently fail if login == True
? Not sure why that would make sense.
Also, the bigger issue is your for-loop; it is overwriting correct data.
For instance, if the first row matches the given credentials, we need to authorise the user. But in your case, the loop will continue and keep checking the rest of the rows, overwriting the value of login
. So when the loop ends, the value of login
is based on the last row.
You need to exit the loop once the correct username and password have been found.
I would also suggest you create a dictionary (dict
) of usernames and passwords from the csv
file first to make your life easier.
来源:https://stackoverflow.com/questions/55278132/how-to-verify-username-and-password-from-csv-file-in-python