close

How to verify username and password from CSV file in Python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to verify username and password from CSV file in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to verify username and password from CSV file in Python?

  1. How to verify username and password from CSV file in Python?

    Firstly, I think you have your conditionals the wrong way round. You currently fail if login == True? Not sure why that would make sense.

  2. verify username and password from CSV file in Python

    Firstly, I think you have your conditionals the wrong way round. You currently fail if login == True? Not sure why that would make sense.

Method 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")

Method 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.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read