Dawid
Dawid

Reputation: 45

How do I load the username from a csv file?

I learned about creating files using python in computer science at school. I have created a piece of code where you can create a username and password and then it saves to a csv file. There is also another option where you can log in. It asks you to enter the username and if it is wrong it says "Username not found". Whatever I enter (even though it is correct) it says Username not found. This is the main part of the code:

Log = input("Enter Choice here: ")
if Log == "Log In" or Log == "log in" or Log == "Log in" or Log == "log In":
    Data = open("F:\\'Filename'.csv", "r")
    SavedUser = Data.readline()
    Username = input("Username: ")
    if Username == SavedUser:
        print("Welcome", Username, "!")
        Password = input("Password: ")
        if Password == Data.readline():
            print("It works")

Thank you for all your help.

Upvotes: 0

Views: 311

Answers (1)

apurvmishra99
apurvmishra99

Reputation: 388

Your CSV file is probably not being read correctly. Python has a csv library to parse CSV files correctly. What you can do is read the CSV file to a dictionary and then compare username and password.

import csv
action = input("Enter Choice here: ")
if action.lower() == "Log In".lower(): #Convert both strings two lowercase and then compare
    reader = csv.reader(open('demo.csv', 'r')) #parsing the csv file correctly
    user_dict = dict(reader) #converting iterable reader directly to a dictionary
    #{'abc': 'abc123', 'username': 'password'}
    username_input = input("Username:")
    if username_input in user_dict: #check if username exists as a key in the dictionary
        print("Welcome", username_input, "!")
        password_input = input("Password: ")
        if password_input == user_dict[username_input]:
            print("It works")

Upvotes: 2

Related Questions