Jump to content

Python CSV help

Aspect11

So let me get straight to the point, my code is supposed to read a .txt file then accept a username and password input form a user and compare it with the input from the user. My current code is:

import csv

def user1Authenticate():
    with open('users.txt', mode='r') as file:
        reader = csv.reader(file)
        users = [(row[0], row[1]) for row in reader]
    user1UsernameInput = input("username: ")
    user1PasswordInput = input("password: ")
    print(users[0])
    if user1UsernameInput == users[0]:
        print("Correct")
        return username
    else:
        print("CREATE NEW USER")

def users():
   print('User 1, Please log in.')
   user1 = user1Authenticate()
   print('User 2, Please log in.')
   #user2 = authentication()
   #print("User 1 is", user1, "and user 2 is", user2)

users()

My file's syntax is 'username, password'.

 

Can you find out what is wrong with it?

 

BTW my teacher said we can only user CSV with text file and not .json files or databases. :(

 

Thanks!

Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to comment
Share on other sites

Link to post
Share on other sites

Other than the obvious that it doesn't check the password input, how can you guarantee that user1 is users[0] or should it be searching the users list to find the user?

6 minutes ago, DerpDiamonds1 said:

if user1UsernameInput == users[0]:

 

¯\_(ツ)_/¯

 

 

Desktop:

Intel Core i7-11700K | Noctua NH-D15S chromax.black | ASUS ROG Strix Z590-E Gaming WiFi  | 32 GB G.SKILL TridentZ 3200 MHz | ASUS TUF Gaming RTX 3080 | 1TB Samsung 980 Pro M.2 PCIe 4.0 SSD | 2TB WD Blue M.2 SATA SSD | Seasonic Focus GX-850 Fractal Design Meshify C Windows 10 Pro

 

Laptop:

HP Omen 15 | AMD Ryzen 7 5800H | 16 GB 3200 MHz | Nvidia RTX 3060 | 1 TB WD Black PCIe 3.0 SSD | 512 GB Micron PCIe 3.0 SSD | Windows 11

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, BobVonBob said:

Other than the obvious that it doesn't check the password input, how can you guarantee that user1 is users[0] or should it be searching the users list to find the user?

 

I was going to do the password verification afterwards, and for the other bit, any user can be assigned to either user1 or user2.

Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to comment
Share on other sites

Link to post
Share on other sites

what is the structure of user1UsernameInput and what is the structure of users[0]

¯\_(ツ)_/¯

 

 

Desktop:

Intel Core i7-11700K | Noctua NH-D15S chromax.black | ASUS ROG Strix Z590-E Gaming WiFi  | 32 GB G.SKILL TridentZ 3200 MHz | ASUS TUF Gaming RTX 3080 | 1TB Samsung 980 Pro M.2 PCIe 4.0 SSD | 2TB WD Blue M.2 SATA SSD | Seasonic Focus GX-850 Fractal Design Meshify C Windows 10 Pro

 

Laptop:

HP Omen 15 | AMD Ryzen 7 5800H | 16 GB 3200 MHz | Nvidia RTX 3060 | 1 TB WD Black PCIe 3.0 SSD | 512 GB Micron PCIe 3.0 SSD | Windows 11

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, BobVonBob said:

what is the structure of user1UsernameInput and what is the structure of users[0]

What do you mean the structure?

Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to comment
Share on other sites

Link to post
Share on other sites

that is to say, user1UsernameInput is a string, and users[0] is a tuple

¯\_(ツ)_/¯

 

 

Desktop:

Intel Core i7-11700K | Noctua NH-D15S chromax.black | ASUS ROG Strix Z590-E Gaming WiFi  | 32 GB G.SKILL TridentZ 3200 MHz | ASUS TUF Gaming RTX 3080 | 1TB Samsung 980 Pro M.2 PCIe 4.0 SSD | 2TB WD Blue M.2 SATA SSD | Seasonic Focus GX-850 Fractal Design Meshify C Windows 10 Pro

 

Laptop:

HP Omen 15 | AMD Ryzen 7 5800H | 16 GB 3200 MHz | Nvidia RTX 3060 | 1 TB WD Black PCIe 3.0 SSD | 512 GB Micron PCIe 3.0 SSD | Windows 11

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, BobVonBob said:

that is to say, user1UsernameInput is a string, and users[0] is a tuple

Yes, but how can I solve it.

Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to comment
Share on other sites

Link to post
Share on other sites

Access the member of the tuple that you need, if you replace the variables in this line

if user1UsernameInput == users[0]:

with their values you get

if 'username' == ('username', 'password'):

which will never be true.

¯\_(ツ)_/¯

 

 

Desktop:

Intel Core i7-11700K | Noctua NH-D15S chromax.black | ASUS ROG Strix Z590-E Gaming WiFi  | 32 GB G.SKILL TridentZ 3200 MHz | ASUS TUF Gaming RTX 3080 | 1TB Samsung 980 Pro M.2 PCIe 4.0 SSD | 2TB WD Blue M.2 SATA SSD | Seasonic Focus GX-850 Fractal Design Meshify C Windows 10 Pro

 

Laptop:

HP Omen 15 | AMD Ryzen 7 5800H | 16 GB 3200 MHz | Nvidia RTX 3060 | 1 TB WD Black PCIe 3.0 SSD | 512 GB Micron PCIe 3.0 SSD | Windows 11

Link to comment
Share on other sites

Link to post
Share on other sites

9 minutes ago, BobVonBob said:

Access the member of the tuple that you need, if you replace the variables in this line


if user1UsernameInput == users[0]:

with their values you get


if 'username' == ('username', 'password'):

which will never be true.

How can i solve that then for multiple users in the file.

Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to comment
Share on other sites

Link to post
Share on other sites

search the users list based on the username

¯\_(ツ)_/¯

 

 

Desktop:

Intel Core i7-11700K | Noctua NH-D15S chromax.black | ASUS ROG Strix Z590-E Gaming WiFi  | 32 GB G.SKILL TridentZ 3200 MHz | ASUS TUF Gaming RTX 3080 | 1TB Samsung 980 Pro M.2 PCIe 4.0 SSD | 2TB WD Blue M.2 SATA SSD | Seasonic Focus GX-850 Fractal Design Meshify C Windows 10 Pro

 

Laptop:

HP Omen 15 | AMD Ryzen 7 5800H | 16 GB 3200 MHz | Nvidia RTX 3060 | 1 TB WD Black PCIe 3.0 SSD | 512 GB Micron PCIe 3.0 SSD | Windows 11

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, BobVonBob said:

search the users list based on the username

How do i do that?

Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to comment
Share on other sites

Link to post
Share on other sites

17 minutes ago, BobVonBob said:

search the users list based on the username

So i think this works, but now it won't let me have multiple users:

def user1Authenticate():
    with open('users.txt', mode='r') as file:
        reader = csv.reader(file)
        users = [(row[0], row[1]) for row in reader]
    user1UsernameInput = input("username: ")
    user1PasswordInput = input("password: ")
    print(users[0])
     if (user1UsernameInput, user1PasswordInput) in  users:
        print("Correct")
        return username
    else:
        print("CREATE NEW USER")

def users():
   print('User 1, Please log in.')
   user1 = user1Authenticate()
   print('User 2, Please log in.')
   #user2 = authentication()
   #print("User 1 is", user1, "and user 2 is", user2)

users()

 

Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to comment
Share on other sites

Link to post
Share on other sites

*bump* as i haven't gotten a response

Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to comment
Share on other sites

Link to post
Share on other sites

I think your approach to the code is wrong, plus it's hard to understand how you want this to work given that you are giving us only a small snippet of the code that calls functions that we do not even see (e.g. authentication() in the comments).

 

Anyhow, what about:

def user1Authenticate():
    with open('users.txt', mode='r') as file:
        reader = csv.reader(file)
        users = []
        for row in reader:
            users.append(row[0] + row[1])
    user1UsernameInput = input("username: ")
    user1PasswordInput = input("password: ")
    print(users[0])
    if (user1UsernameInput + user1PasswordInput) in users:
        print("Correct")
        return username
    else:
        print("CREATE NEW USER")

def users():
   print('User 1, Please log in.')
   user1 = user1Authenticate()
   print('User 2, Please log in.')
   #user2 = authentication()
   #print("User 1 is", user1, "and user 2 is", user2)

users()

For example, where is the username variable being grabbed from? The code, written like that, is not really going to work.

CPU: Ryzen 7 5800X Cooler: Corsair H100i Platinum SE Mobo: Asus B550-A GPU: EVGA RTX 2070 XC RAM: G.Skill Trident Z RGB 3200MHz 16CL 4x8GB (DDR4) SSD0: Crucial MX300 525GB SSD1: Samsung QVO 1TB PSU: NZXT C650 Case: Corsair 4000D Airflow Monitor: Asus VG259QM (240Hz)

I usually edit my posts immediately after posting them, as I don't check for typos before pressing the shiny SUBMIT button.

Unraid Server

CPU: Ryzen 5 7600 Cooler: Noctua NH-U12S Mobo: Asus B650E-i RAM: Kingston Server Premier ECC 2x32GB (DDR5) SSD: Samsung 980 2x1TB HDD: Toshiba MG09 1x18TB; Toshiba MG08 2x16TB HDD Controller: LSI 9207-8i PSUCorsair SF750 Case: Node 304

Link to comment
Share on other sites

Link to post
Share on other sites

11 hours ago, Nocte said:

I think your approach to the code is wrong, plus it's hard to understand how you want this to work given that you are giving us only a small snippet of the code that calls functions that we do not even see (e.g. authentication() in the comments).

 

Anyhow, what about:


def user1Authenticate():
    with open('users.txt', mode='r') as file:
        reader = csv.reader(file)
        users = []
        for row in reader:
            users.append(row[0] + row[1])
    user1UsernameInput = input("username: ")
    user1PasswordInput = input("password: ")
    print(users[0])
    if (user1UsernameInput + user1PasswordInput) in users:
        print("Correct")
        return username
    else:
        print("CREATE NEW USER")

def users():
   print('User 1, Please log in.')
   user1 = user1Authenticate()
   print('User 2, Please log in.')
   #user2 = authentication()
   #print("User 1 is", user1, "and user 2 is", user2)

users()

For example, where is the username variable being grabbed from? The code, written like that, is not really going to work.

Just asking, but what is wrong with my approach? Anyway I finished it and here is the final code:

import random
import csv
import time
import sys

def storeWinners(winner, winningScore, user1Score, user2Score):
   file = open("scores.txt", "a")
   file.write("\n" + winner + ", " + winningScore)
   file.close()

def finalDecide(user1Score, user2Score, user1, user2, i):
   if user1Score > user2Score:
      winner = user1
      winningScore = str(user1Score)
      print("*------------------------------------------------------------*")
      print("The winner for this game is", user1)
      print("*------------------------------------------------------------*")
      storeWinners(winner, winningScore, user1Score, user2Score)
   elif user2Score > user1Score:
      winner = user2
      winningScore = str(user2Score)
      print("*------------------------------------------------------------*")
      print("The winner for this game is", user2)
      print("*------------------------------------------------------------*")
      storeWinners(winner, winningScore, user1Score, user2Score)
   elif user1Score == user2Score:
      print("This is a special occurence as both users have the same score, so we will roll again until one user is higher than the other user!\n")
      while user1Score == user2Score:
         time.sleep(1)
         user1FinalRoll = random.randint(1,6)
         user2FinalRoll = random.randint(1,6)
         user1Score = user1Score + user1FinalRoll
         user2Score = user2Score + user2FinalRoll
         print("\t For round", i + 2, user1, "got", user1Score, "and", user2, "got", user2Score)
         i = i + 1
      time.sleep(1)
      if user1Score > user2Score:
         winner = user1
         winningScore = str(user1Score)
         print("*------------------------------------------------------------*")
         print("The winner for this game is", user1)
         print("*------------------------------------------------------------*")
         storeWinners(winner, winningScore, user1Score, user2Score)
      elif user2Score > user1Score:
         winner = user2
         winningScore = str(user2Score)
         print("*------------------------------------------------------------*")
         print("The winner for this game is", user2)
         print("*------------------------------------------------------------*")
         storeWinners(winner, winningScore, user1Score, user2Score)

def rollDieWithPoints(user1, user2):
   print("*------------------------------------------------------------*")
   print("Now for the main game, please wait as the program calculates each user's score!")
   print("The scores for each round are as follows, keep in mind that these scores are completely random:\n")
   user1Score = 0
   user2Score = 0
   for i in range(0, 5):
      time.sleep(1)
      user1Roll1 = random.randint(1,6)
      user1Roll2 = random.randint(1,6)
      user2Roll1 = random.randint(1,6)
      user2Roll2 = random.randint(1,6)
      user1Score = user1Score + user1Roll1 + user1Roll2
      user2Score = user2Score + user2Roll1 + user2Roll2
      def user1Points(user1Score):
         if (user1Score % 2 == 0):
            user1Score = user1Score + 10
            if user1Roll1 == user1Roll2:
               user1Roll3 = random.randint(1,6)
               user1Score = user1Score + user1Roll3
         elif (user1Score % 2 != 0) and (user1Score - 5 >= 0):
            user1Score = user1Score - 5
            if user1Roll1 == user1Roll2:
               user1Roll3 = random.randint(1,6)
               user1Score = user1Score + user1Roll3
         else:
            print("I'm sorry there was an error, please try again later")
      def user2Points(user2Score):
         if (user2Score % 2 == 0):
            user2Score = user2Score + 10
            if user2Roll1 == user2Roll2:
               user2Roll3 = random.randint(1,6)
               user2Score = user2Score + user2Roll3
         elif (user2Score % 2 != 0) and (user2Score - 5 >= 0):
            user2Score = user2Score - 5
            if user2Roll1 == user2Roll2:
               user2Roll3 = random.randint(1,6)
               user2Score = user2Score + user2Roll3
         else:
            print("I'm sorry there was an error, please try again later")
      user1Points(user1Score)
      user2Points(user2Score)
      print("\t For round", i + 1, user1, "got", user1Score, "and", user2, "got", user2Score)
      time.sleep(1)
   print("\nNow that all the points are accounted for, we can see who won!")
   finalDecide(user1Score, user2Score, user1, user2, i)

def user1Authenticate():
    with open('users.txt', mode='r') as file:
        reader = csv.reader(file)
        users = [(row[0], row[1]) for row in reader]
    user1UsernameInput = input("Please input your username: ")
    user1PasswordInput = input("Please input your password: ")
    if (user1UsernameInput,user1PasswordInput) in users:
        print("Correct credentials, you are now logged in with username", user1UsernameInput)
        return user1UsernameInput
    elif (user1UsernameInput) not in users:
        newUsernameInput = input("That username is not in the system, would you like to create a new user by that name? (Y/N): ")
        if newUsernameInput == "Y":
          file = open("users.txt", "a")
          newUsernamePasswordInput = input("Please enter your password?: ")
          file.write("\n" + user1UsernameInput + "," + newUsernamePasswordInput)
          file.close()
          print("New username and password registered, please run the program again!")
          sys.exit()
        elif newUsernameInput == "N":
          print("Okay, wrong username, please try again!")
          sys.exit()
        else:
          print("That is not an input, please try again!")
          sys.exit()
    else:
        print("I'm sorry there was an error, please try again later")
        sys.exit()

def user2Authenticate():
    with open('users.txt', mode='r') as file:
        reader = csv.reader(file)
        users = [(row[0], row[1]) for row in reader]
    user2UsernameInput = input("Please input your username: ")
    user2PasswordInput = input("Please input your password: ")
    if (user2UsernameInput,user2PasswordInput) in users:
        print("Correct credentials, you are now logged in with username", user2UsernameInput)
        return user2UsernameInput
    elif (user2UsernameInput) not in users:
        newUsernameInput = input("That username is not in the system, would you like to create a new user by that name? (Y/N): ")
        if newUsernameInput == "Y":
          file = open("users.txt", "a")
          newUsernamePasswordInput = input("Please enter your password?: ")
          file.write("\n" + user2UsernameInput + "," + newUsernamePasswordInput)
          file.close()
          print("New username and password registered, please run the program again!")
          sys.exit()
        elif newUsernameInput == "N":
          print("Okay, wrong username, please try again!")
          sys.exit()
        else:
          print("That is not an input, please try again!")
          sys.exit()
    else:
        print("I'm sorry there was an error, please try again later")
        sys.exit()

def users():
   print('User 1, Please log in.')
   user1 = user1Authenticate()
   print('User 2, Please log in.')
   user2 = user2Authenticate()
   print("Time to play the game!")
   rollDieWithPoints(user1, user2)

def printScores(n):
   print("*------------------------------------------------------------*")
   with open('scores.txt', mode='r') as file:
      reader = csv.reader(file)
      scores = [(row[0], int(row[1])) for row in reader]
   scores = sorted(scores, key=lambda score: score[1], reverse=True)[:n]
   if len(scores) > 0:
      print("The top {} scores are:\n".format(n))
      pos = 1
      for name, score in scores:
         print("\t{}. {} with {}.".format(pos, name, score))
         pos += 1
   else:
      print("There are no scores on the leaderboard right now, play the game to earn scores for each user!")

def start():
   print("*----------* Welcome to my dice rolling game! *----------*")
   print("Pick an option below to either play the game or check the scores!")
   startingChoice = input("Do you want to play the game (1) or check scores (2)?: ")
   if startingChoice == "1":
      users()
   elif startingChoice == "2":
      printScores(5)
   else:
      print("That is not an input, please try again")

start()

 

Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to comment
Share on other sites

Link to post
Share on other sites

Now that I've seen the whole code it is fine.

I was saying it was a bad approach because, for example, you were authenticating via a text file which is not exactly top level security. :) But if it's a local dice game then it's not problematic.

CPU: Ryzen 7 5800X Cooler: Corsair H100i Platinum SE Mobo: Asus B550-A GPU: EVGA RTX 2070 XC RAM: G.Skill Trident Z RGB 3200MHz 16CL 4x8GB (DDR4) SSD0: Crucial MX300 525GB SSD1: Samsung QVO 1TB PSU: NZXT C650 Case: Corsair 4000D Airflow Monitor: Asus VG259QM (240Hz)

I usually edit my posts immediately after posting them, as I don't check for typos before pressing the shiny SUBMIT button.

Unraid Server

CPU: Ryzen 5 7600 Cooler: Noctua NH-U12S Mobo: Asus B650E-i RAM: Kingston Server Premier ECC 2x32GB (DDR5) SSD: Samsung 980 2x1TB HDD: Toshiba MG09 1x18TB; Toshiba MG08 2x16TB HDD Controller: LSI 9207-8i PSUCorsair SF750 Case: Node 304

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×